原生 JS 完整實現(可直接運行)
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>動態表格增刪</title>
<style>
table { border-collapse:collapse; width:100%; max-width:800px; margin:10px auto; }
th, td { border:1px solid #ddd; padding:8px; text-align:center; }
th { background:#f5f5f5; }
.btn { padding:4px 12px; margin:0 5px; cursor:pointer; }
.btn-danger { background:#dc3545; color:#fff; border:none; border-radius:3px; }
.btn-primary { background:#007bff; color:#fff; border:none; border-radius:3px; }
</style></head><body>
<table id="data-table">
<thead>
<tr><th>#</th><th>姓名</th><th>郵箱</th><th>電話</th><th>操作</th></tr>
</thead>
<tbody></tbody>
</table>
<div style="text-align:center; max-width:800px; margin:0 auto;">
<button class="btn btn-primary" onclick="addRow()">+ 添加行</button>
<button class="btn btn-danger" onclick="clearAll()">清空所有</button>
</div>
<script>
let rowIdCounter = 1;
function addRow(data = {}) {
const tbody = document.querySelector('#data-table tbody');
const tr = document.createElement('tr');
tr.dataset.id = rowIdCounter++; // 唯一標識
tr.innerHTML = `
<td>${tbody.rows.length + 1}</td>
<td><input type="text" value="${escapeHtml(data.name||'')}" placeholder="姓名"></td>
<td><input type="email" value="${escapeHtml(data.email||'')}" placeholder="郵箱"></td>
<td><input type="tel" value="${escapeHtml(data.phone||'')}" placeholder="電話"></td>
<td><button class="btn btn-danger" onclick="deleteRow(this)">刪除</button></td>
`;
tbody.appendChild(tr);
updateIndexes();
}
function deleteRow(btn) {
const tr = btn.closest('tr');
tr.remove();
updateIndexes();
}
function clearAll() {
if (confirm('確定清空所有數據?')) {
document.querySelector('#data-table tbody').innerHTML = '';
rowIdCounter = 1;
addRow(); // 保留一行空白
}
}
function updateIndexes() {
const rows = document.querySelectorAll('#data-table tbody tr');
rows.forEach((tr, i) => tr.cells[0].textContent = i + 1);
}
// 簡單 XSS 防護
function escapeHtml(str) {
return String(str).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
}
// 初始化一行
addRow();
</script>
</body></html>
核心 API 解析
| 操作 | 關鍵 DOM API | 說明 |
| 創建行 | `tbody.insertRow()` / `document.createElement('tr')` | `insertRow` 自動處理 tbody,推薦用 `createElement` 靈活構建 HTML |
| 創建單元格 | `tr.insertCell()` / `document.createElement('td')` | 同理 |
| 刪除行 | `tr.remove()` (現代) / `tbody.deleteRow(index)` (舊) | `remove()` 直接移除元素,無需索引 |
| 查找行 | `btn.closest('tr')` | 向上查找最近祖先 tr,極其方便 |
| 重新編號 | `tbody.rows` 集合即時更新 | 遍歷 `rows` 修改 `cells[0]` 即可 |
數據綁定增強版(分離關注點)
// 數據層
const tableData = [
{id:1, name:'張三', email:'zhang@example.com', phone:'13800000001'},
{id:2, name:'李四', email:'li@example.com', phone:'13800000002'}
];
// 渲染層
function render() {
const tbody = document.querySelector('#data-table tbody');
tbody.innerHTML = tableData.map((row, i) => `
<tr data-id="${row.id}">
<td>${i+1}</td>
<td>${escapeHtml(row.name)}</td>
<td>${escapeHtml(row.email)}</td>
<td>${escapeHtml(row.phone)}</td>
<td><button class="btn btn-danger" onclick="removeById(${row.id})">刪除</button></td>
</tr>
`).join('');
}
function removeById(id) {
const idx = tableData.findIndex(r => r.id === id);
if (idx > -1) { tableData.splice(idx, 1); render(); }
}
function addRow() {
tableData.push({id:Date.now(), name:'', email:'', phone:''});
render();
}
現代框架對比
| 框架 | 核心思想 | 代碼量 | 維護性 |
| Vue 3 | `v-for="row in rows"` + `@click="remove(row.id)"` + 響應式數組 | 極少 | 極高 |
| React | `rows.map(row => |
)` + `setRows(r=>r.filter(...))`| 少 | 高 |
| 原生 JS | 手動 DOM 操作 / 重渲染 innerHTML | 多 | 中(易漏同步) |
總結
原生 JS 通過 `createElement`/`appendChild`/`remove`/`closest` 即可實現完整增刪功能,關鍵點在於**維護唯一標識**與**重新編號**。現代項目強烈建議使用 Vue/React 等框架,將 DOM 操作交給虛擬 DOM,專注於數據狀態管理。