萬盛學電腦網

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

JavaScript 動態向表格新增列:insertRow() 完整指南

核心方法

`HTMLTableElement.insertRow(index)` 可在表格中插入新列(``)。索引 `0` 表示插在最頂端(表頭之後),`-1` 或省略表示插在最後。

完整範例

<!DOCTYPE html>
<html>
<head>
  <script>
    function insRow() {
      var table = document.getElementById('myTable');
      var row = table.insertRow(0); // 插入到最頂端(索引 0)

      var cell1 = row.insertCell(0);
      var cell2 = row.insertCell(1);
      cell1.innerHTML = "NEW CELL1";
      cell2.innerHTML = "NEW CELL2";
    }
  </script>
</head>
<body>
  <table id="myTable" border="1">
    <tr><td>Row1 cell1</td><td>Row1 cell2</td></tr>
    <tr><td>Row2 cell1</td><td>Row2 cell2</td></tr>
    <tr><td>Row3 cell1</td><td>Row3 cell2</td></tr>
  </table>
  <br>
  <input type="button" onclick="insRow()" value="Insert row">
</body>
</html>

執行效果

  • 每次點擊按鈕,表格最上方新增一列,內容為 "NEW CELL1"、"NEW CELL2"
  • 原有列依序下移

進階封裝:彈性新增列函式

function addRow(tableId, dataArray, position = -1) {
  var table = document.getElementById(tableId);
  if (!table) return null;

  var row = table.insertRow(position);
  dataArray.forEach(function(text, i) {
    var cell = row.insertCell(i);
    cell.innerHTML = text;
  });
  return row;
}

// 使用範例
addRow('myTable', ['A1', 'B1'], 0);     // 頂端新增
addRow('myTable', ['A2', 'B2'], -1);    // 底端新增
addRow('myTable', ['A3', 'B3'], 2);     // 插入到第 3 列位置(索引 2)

刪除列:deleteRow()

function deleteRow(tableId, index) {
  var table = document.getElementById(tableId);
  if (table.rows[index]) table.deleteRow(index);
}

// 刪除第一列
deleteRow('myTable', 0);
// 刪除最後一列
deleteRow('myTable', -1);

完整 CRUD 範例:動態表格管理

<style>
  table { border-collapse: collapse; width: 100%; }
  th, td { border: 1px solid #ccc; padding: 8px; }
  .actions button { margin-right: 4px; }
</style>

<table id="dataTable">
  <thead><tr><th>Name</th><th>Age</th><th>Action</th></tr></thead>
  <tbody></tbody>
</table>
<div class="actions">
  <input id="name" placeholder="Name">
  <input id="age" type="number" placeholder="Age">
  <button onclick="addData()">新增</button>
</div>

<script>
function addData() {
  var name = document.getElementById('name').value;
  var age = document.getElementById('age').value;
  if (!name || !age) return alert('請填寫完整');

  var tbody = document.querySelector('#dataTable tbody');
  var row = tbody.insertRow(-1);
  row.insertCell(0).textContent = name;
  row.insertCell(1).textContent = age;
  var btnCell = row.insertCell(2);
  btnCell.innerHTML = '';

  document.getElementById('name').value = '';
  document.getElementById('age').value = '';
}
</script>

總結

  • `table.insertRow()` + `row.insertCell()` 是動態表格操作的黃金組合。
  • 搭配 `deleteRow()`/`deleteCell()` 可實作完整 CRUD 介面。
  • 現代專案建議搭配 `