要在一列前面多塞一格,不必組 HTML 字串,直接用 insertCell 就好。它會自動處理好 cell 的掛載與位置。
<!DOCTYPE html>
<html>
<head>
<script>
function insCell() {
var x = document.getElementById('tr1').insertCell(0);
x.innerHTML = "The famous";
}
</script>
</head>
<body>
<table border="1">
<tr id="tr1"><td>Peter</td><td>Griffin</td></tr>
</table>
<br>
<input type="button" onclick="insCell()" value="Insert cell" />
</body>
</html>語法為 tr.insertCell(index):
· index 為要插入的位置,0 表示最前面。
· 省略參數或傳入 -1 時,會附加到該列最後。
· 回傳值是新建立的 HTMLTableCellElement,可以直接接著設定內容。
它會自動把新 cell 插在正確節點位置上,並同步更新該列的 cells 集合,這是它比 appendChild 方便的地方——後者永遠只能加在尾端。
這是最容易忽略的問題。表格的每一列欄數不一致時,瀏覽器會依「欄數最多的那一列」決定總欄數,其餘列不足的位置會自動補上空白格,導致資料錯位。
var table = document.getElementById('myTable');
// 為每一列都插入一格,維持欄數一致
Array.prototype.forEach.call(table.rows, function(row) {
var cell = row.insertCell(0);
cell.innerHTML = "-";
});如果這一格是「序号」或「勾選欄」,通常每一列都要有,用迴圈一次處理最安全。
插入的內容若來自外部資料,請用 textContent:
var cell = document.getElementById('tr1').insertCell(0);
cell.textContent = userInput; // 安全,會被視為純文字insertCell 產生的永遠是 td。若你需要 th,得自己建立節點:
var th = document.createElement('th');
th.textContent = "序號";
document.getElementById('tr1').insertBefore(th, document.getElementById('tr1').firstChild);若表格由資料驅動,更乾淨的做法是在資料模型裡就補上這個欄位,然後重新渲染整張表格;只有在「使用者互動觸發局部新增」的情境,直接操作 DOM 才最有效率。 Frequent 反覆增刪時,也建議搭配 DocumentFragment 批次處理,減少重排次數。