Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

แอตทริบิวต์ headers: ผูกเซลล์ตารางกับ Header Cells ใน HTML

แอตทริบิวต์ headers ใช้ใน <td> หรือ <th> เพื่อระบุ id ของ Header Cell (<th>) ที่เซลล์นี้เกี่ยวข้อง ช่วย Screen Readers อ่าน Header ก่อน Data Cell ทำให้ Accessibility ดีกว่า (Section 508, WCAG)

ตัวอย่างการใช้งาน

<!DOCTYPE html>
<html>
<head>
    <style>
        table, th, td { border: 2px solid blue; border-collapse: collapse; padding: 8px; }
        th { background: #007bff; color: white; }
    </style>
</head>
<body>
    <table>
        <tr>
            <th id="name">รหัสวิชา</th>
            <th id="email">ชื่อวิชา</th>
        </tr>
        <tr>
            <td headers="name">001</td>
            <td headers="email">คณิตศาสตร์</td>
        </tr>
        <tr>
            <td headers="name">002</td>
            <td headers="email">ฟิสิกส์</td>
        </tr>
    </table>
</body>
</html>

หลาย Headers (Complex Tables)

เซลล์หนึ่งอาจเกี่ยวข้องกับหลาย Header (เช่น Row Header + Column Header):

<table>
    <tr>
        <th id="r1">Q1</th>
        <th id="r2">Q2</th>
        <th id="r3">Q3</th>
        <th id="r4">Q4</th>
    </tr>
    <tr>
        <th id="prodA">Product A</th>
        <td headers="prodA r1">100</td>
        <td headers="prodA r2">150</td>
        <td headers="prodA r3">200</td>
        <td headers="prodA r4">250</td>
    </tr>
    <tr>
        <th id="prodB">Product B</th>
        <td headers="prodB r1">80</td>
        <td headers="prodB r2">120</td>
        <td headers="prodB r3">180</td>
        <td headers="prodB r4">220</td>
    </tr>
</table>

Scope Attribute (ทางเลือกที่ง่ายกว่า)

สำหรับตารางเรียบง่าย ใช้ scope บน <th> แทน headers บน <td>:

<th scope="col">ชื่อ</th>        <!-- Column Header -->
<th scope="row">สินค้า A</th>  <!-- Row Header -->
<th scope="colgroup">Q1-Q2</th> <!-- Column Group Header -->
<th scope="rowgroup">2024</th>  <!-- Row Group Header -->

เมื่อไหร่ควรใช้ headers แทน scope?

  • ตารางซับซ้อน: Multi-level Headers, Irregular Structure
  • เซลล์ข้ามหลาย Column/Row (colspan, rowspan)
  • ต้องการความแม่นยำสูงสุดสำหรับ Screen Readers
  • Data Tables ขนาดใหญ่ที่มี Header ซ้อนกันหลายชั้น

Accessibility Testing

  • Screen Reader (NVDA, JAWS, VoiceOver) - ฟังว่าอ่าน Header ก่อน Data หรือไม่
  • axe DevTools / WAVE - ตรวจสอบ Table Accessibility
  • Keyboard Navigation - Tab ผ่าน Table ได้ถูกต้อง