萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

DOM 操作 HTML Table 完全指南:動態增刪改查與最佳實踐

前言

<table> 結構嚴謹,原生 DOM 提供專屬 API(insertRow、insertCell、deleteRow、deleteCell、rows、cells 集合),比通用 createElement/appendChild 更語義化、效能更高。本文系統梳理表格動態操作全流程。

核心 DOM 集合與屬性

屬性/集合所屬對象說明
table.rowsHTMLTableElement所有 <tr>(含 thead/tbody/tfoot 內)
tbody.rowsHTMLTableSectionElement該區塊內的行
tr.cellsHTMLTableRowElement該行所有 <td>/<th>
tr.rowIndexHTMLTableRowElement在整個 table 中的行索引
tr.sectionRowIndexHTMLTableRowElement在所屬 thead/tbody/tfoot 中的行索引
HTMLTableCellElement在行中的列索引

一、動態新增行與儲存格

insertRow(index) / insertCell(index)

  • index:插入位置索引,-1 或省略 = 追加到末尾
  • 回傳新建的 HTMLTableRowElement / HTMLTableCellElement
var table = document.getElementById('member');

// 在 tbody 末尾新增一行(推薦操作 tbody)
var tbody = table.tBodies[0] || table; // 若無 tbody 則直接操作 table
var row = tbody.insertRow(-1); // 等同 tbody.insertRow(tbody.rows.length)

// 批量填充儲存格
var data = ['fresheggs', 'W610', 'Nov 5th', 'Scorpio', '1038818'];
data.forEach(function (text, i) {
  var cell = row.insertCell(i);
  cell.textContent = text; // 防 XSS,優於 innerHTML
});

完整可運行示例:動態新增會員列表

<table id="member" class="datalist">
  <caption>Member List</caption>
  <thead>
    <tr><th>Name</th><th>Class</th><th>Birthday</th><th>Constellation</th><th>Mobile</th></tr>
  </thead>
  <tbody>
    <tr><td>isaac</td><td>W13</td><td>Jun 24th</td><td>Cancer</td><td>1118159</td></tr>
    <tr><td>girlwing</td><td>W210</td><td>Sep 16th</td><td>Virgo</td><td>1307994</td></tr>
  </tbody>
</table>
<button id="addRow">新增一行</button>

<script>
document.getElementById('addRow').onclick = function () {
  var table = document.getElementById('member');
  var tbody = table.tBodies[0] || table;
  var row = tbody.insertRow(-1);
  var data = ['newUser', 'W999', 'Jan 1st', 'Capricorn', '9999999'];
  data.forEach(function (txt, i) {
    row.insertCell(i).textContent = txt;
  });
};
</script>

二、修改儲存格內容

直接索引訪問(最高效)

var table = document.getElementById('table1');
// 修改第 5 行(索引4)第 6 列(索引5)
table.rows[4].cells[5].innerHTML = 'good'; // 或 .textContent = 'good'

遍歷修改:批量更新某列

// 將第 3 列(索引2)所有儲存格加上前綴
for (var i = 0; i < table.rows.length; i++) {
  var cell = table.rows[i].cells[2];
  if (cell) cell.textContent = 'UPDATED: ' + cell.textContent;
}

三、刪除行與列

刪除行:deleteRow(index)

// 刪除表格第 3 行(索引2)
table.deleteRow(2);

// 刪除 tbody 內第 1 行
table.tBodies[0].deleteRow(0);

刪除列:無原生 API,需逐行刪除儲存格

function deleteColumn(table, colIndex) {
  for (var i = 0; i < table.rows.length; i++) {
    var row = table.rows[i];
    if (row.cells.length > colIndex) {
      row.deleteCell(colIndex);
    }
  }
}

// 使用
deleteColumn(document.getElementById('table1'), 2); // 刪除第 3 列

四、進階技巧與效能優化

1. DocumentFragment 批量掛載

function appendRows(table, rowsData) {
  var tbody = table.tBodies[0] || table;
  var frag = document.createDocumentFragment();

  rowsData.forEach(function (rowData) {
    var row = document.createElement('tr');
    rowData.forEach(function (cellText) {
      var td = document.createElement('td');
      td.textContent = cellText;
      row.appendChild(td);
    });
    frag.appendChild(row);
  });

  tbody.appendChild(frag); // 單次重排
}

2. 虛擬滾動 / 分頁

大數據量(>1000 行)建議:

  • 只渲染可視區 + 緩衝區
  • 使用 TanStack Virtual(React/Vue/Solid)或原生 IntersectionObserver 實現

3. 編輯模式切換

function makeCellEditable(cell) {
  var original = cell.textContent;
  var input = document.createElement('input');
  input.value = original;
  input.style.width = '100%';
  cell.textContent = '';
  cell.appendChild(input);
  input.focus();

  function save() {
    cell.textContent = input.value;
    cell.onclick = edit; // 恢復點擊編輯
  }

  input.addEventListener('blur', save);
  input.addEventListener('keydown', function (e) {
    if (e.key === 'Enter') save();
    if (e.key === 'Escape') { cell.textContent = original; cell.onclick = edit; }
  });

  cell.onclick = null; // 防止重複觸發
}

table.querySelectorAll('td').forEach(function (td) {
  td.onclick = function () { makeCellEditable(td); };
});

五、語義化結構建議

<table>
  <caption>表格標題(無障礙必備)</caption>
  <thead>
    <tr><th scope="col">列標題</th>...</tr>
  </thead>
  <tbody>
    <tr><th scope="row">行標題</th><td>數據</td>...</tr>
  </tbody>
  <tfoot>
    <tr><td colspan="...">摘要/統計</td></tr>
  </tfoot>
</table>

結語

原生 Table DOM API 設計精巧,善用 rows/cells 集合與 insertRow/insertCell/deleteRow/deleteCell 四大核心方法,配合 DocumentFragment 批量操作,即可高效實現複雜表格交互。現代專案若涉及大量數據、排序、篩選、編輯,建議引入 TanStack Table、AG Grid 等專業表格庫。

copyright © 萬盛學電腦網 all rights reserved