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

เมธอด createTFoot() ของตารางใน HTML DOM: สร้างท้ายตาราง <tfoot>

เมธอด createTFoot() คืออะไร?

เมธอด createTFoot() ของออบเจ็กต์ตาราง (HTMLTableElement) ใช้ **สร้างเอลิเมนต์ <tfoot> ว่าง** และเพิ่มเข้าไปในตาราง (วางท้ายตาราง เสมอ) หากตารางมี <tfoot> อยู่แล้ว จะคืนค่า tfoot เดิม (ไม่สร้างใหม่)

รูปแบบการใช้งาน (Syntax)

tableElement.createTFoot()

คืนค่า: HTMLTableSectionElement (เอลิเมนต์ tfoot ที่สร้างหรือมีอยู่แล้ว)

ตัวอย่าง: สร้างท้ายตาราง

<!DOCTYPE html>
<html>
<style>
  body { color: #000; background: lightblue; height: 100vh; text-align: center; }
  table { margin: 2rem auto; border-collapse: collapse; }
  th, td { border: 1px solid #333; padding: 8px; }
  caption { color: #db133a; font-weight: bold; padding: 0.5rem; }
  .btn { background: #db133a; border: none; height: 2rem; border-radius: 2px; width: 40%; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem auto; }


การใช้งานร่วมกับ deleteTFoot()

function resetFooter() {
  var table = document.querySelector('table');
  table.deleteTFoot();        // ลบ tfoot เก่า (ถ้ามี)
  var tfoot = table.createTFoot(); // สร้างใหม่
  tfoot.innerHTML = '<tr><td colspan="2">ท้ายตารางใหม่</td></tr>';
}

ความสำคัญของ <tfoot>

  • **Semantic:** บอกว่าเป็นส่วนสรุป/ท้ายตาราง
  • **Placement:** ใน HTML เขียนก่อน <tbody> ก็ได้ (HTML5) แต่เบราว์เซอร์จะ **แสดงท้ายตารางเสมอ**
  • **Printing:** บางเบราว์เซอร์พิมพ์ <tfoot> ท้ายทุกหน้า
  • **Data Summary:** ใช้แสดง ผลรวม (Sum), ค่าเฉลี่ย (Average), จำนวน (Count) ฯลฯ

ตัวอย่าง: คำนวณผลรวมอัตโนมัติใน tfoot

<table id="salesTable">
  <thead><tr><th>สินค้า</th><th>ราคา</th></tr></thead>
  <tbody>
    <tr><td>สินค้า A</td><td class="price">100</td></tr>
    <tr><td>สินค้า B</td><td class="price">250</td></tr>
    <tr><td>สินค้า C</td><td class="price">150</td></tr>
  </tbody>
</table>

<script>
  var table = document.getElementById('salesTable');
  var tfoot = table.createTFoot();
  var sum = 0;
  table.querySelectorAll('.price').forEach(function(td) {
    sum += parseFloat(td.textContent) || 0;
  });
  tfoot.innerHTML = '<tr><th>รวม</th><th>' + sum + '</th></tr>';
</script>

เมธอดจัดการส่วนของตาราง (สรุป)

ส่วน สร้าง (Create) ลบ (Delete)
<caption>createCaption()deleteCaption()
<thead>createTHead()deleteTHead()
<tfoot>createTFoot()deleteTFoot()

ข้อควรระวัง

  • createTFoot() สร้าง <tfoot> **ว่างเปล่า** ต้องใส่ <tr> และ <td>/<th> เอง
  • มีได้สูงสุด **1 <tfoot> ต่อตาราง**
  • ใช้ table.tFoot เพื่อเข้าถึง tfoot ที่มีอยู่ (คืนค่า null ถ้าไม่มี)
  • ใน HTML เขียน <tfoot> ก่อน <tbody> ได้ (HTML5) แต่มักเขียนท้ายเพื่ออ่านง่าย