表格動態增刪是後台管理、數據錄入的高頻需求。本文使用原生 HTMLTableElement API(insertRow、insertCell、deleteRow),配合事件代理實現高效、無依賴的增刪交互,並處理表單字段 name 數組化提交。
const table = document.getElementById('data-table');
const row = table.insertRow(index); // index=-1 或省略 為末尾
const cell = row.insertCell(index); // 返回 HTMLTableCellElement
cell.innerHTML = '<input name="items[0].name">';
table.deleteRow(rowIndex); // 刪除指定索引行
<table id="data-table">
<thead><tr><th>產品</th><th>數量</th><th>單價</th><th>操作</th></tr></thead>
<tbody></tbody>
</table>
<button id="add-row">新增行</button>
<script>
const tbody = document.querySelector('#data-table tbody');
let rowIndex = 0;
document.getElementById('add-row').addEventListener('click', () => {
const row = tbody.insertRow();
row.dataset.index = rowIndex;
row.innerHTML = `
<td><input name="items[${rowIndex}].name" required></td>
<td><input name="items[${rowIndex}].qty" type="number" min="1" value="1"></td>
<td><input name="items[${rowIndex}].price" type="number" step="0.01"></td>
<td><button type="button" class="del-btn">刪除</button></td>
`;
rowIndex++;
});
// 事件代理:刪除按鈕
tbody.addEventListener('click', e => {
if (e.target.matches('.del-btn')) {
const row = e.target.closest('tr');
row.remove(); // 現代 API,等同 deleteRow(row.rowIndex)
// 可選:重新索引 name 屬性以保持連續
reindexNames();
}
});
function reindexNames() {
[...tbody.rows].forEach((row, i) => {
row.querySelectorAll('[name]').forEach(input => {
input.name = input.name.replace(/items\[\d+\]/, `items[${i}]`);
});
});
}
</script>
cell.contentEditable = true + blur 保存。SortableJS,調整行順序後同步 name 索引。List<Item> items,自動綁定數組索引。reindexNames 可改用 dataset.index 並在提交時統一重建 name。