在 Web 表單、資料錄入介面中,動態新增/刪除表格列是常見需求。本文提供一個完整、可直接執行的單檔案範例,涵蓋建立元素、綁定事件、DOM 操作全流程,並說明關鍵 API 用法。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>表格動態增刪列 Demo</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
table { border-collapse: collapse; width: 100%; max-width: 600px; margin: 20px 0; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background: #f5f5f5; }
button { margin-right: 8px; padding: 6px 12px; cursor: pointer; }
</style>
</head>
<body>
<table id="data-table">
<thead>
<tr><th>名稱</th><th>數值</th><th>操作</th></tr>
</thead>
<tbody>
<tr><td>初始資料 1</td><td>100</td><td><button class="btn-del">刪除</button></td></tr>
<tr><td>初始資料 2</td><td>200</td><td><button class="btn-del">刪除</button></td></tr>
</tbody>
</table>
<button id="btn-add">新增列</button>
<button id="btn-clear">清空所有</button>
<script>
$(function () {
var $table = $('#data-table');
var $tbody = $table.find('tbody');
var rowCounter = 3; // 用於生成唯一名稱
// 1. 新增列
$('#btn-add').on('click', function () {
var $tr = $('<tr>');
$tr.append('<td>新資料 ' + rowCounter + '</td>');
$tr.append('<td>' + (rowCounter * 100) + '</td>');
$tr.append('<td><button class="btn-del">刪除</button></td>');
$tbody.append($tr);
rowCounter++;
});
// 2. 刪除列(事件委派,支援動態新增的按鈕)
$tbody.on('click', '.btn-del', function () {
$(this).closest('tr').remove();
});
// 3. 清空所有資料列(保留表頭)
$('#btn-clear').on('click', function () {
$tbody.empty();
rowCounter = 1;
});
});
</script>
</body>
</html>
// jQuery 方式(推薦:可鏈式、自動處理 HTML 字串)
var $tr = $('內容 ');
// 原生方式(效能略高,適合大量建立)
var tr = document.createElement('tr');
var td = document.createElement('td');
td.textContent = '內容';
tr.appendChild(td);
// 錯誤:直接綁定,動態新增的 .btn-del 不生效
// $('.btn-del').on('click', ...);
// 正確:委派給靜態父層(tbody)
$tbody.on('click', '.btn-del', function () { ... });
$(this).closest('tr').remove(); // 向上找最近的 tr 並移除
$tbody.empty(); // 僅清空 tbody,thead 保留
td 切換為 <input>,失焦存回。jQuery UI Sortable 或 SortableJS 實現列拖曳重排。$tbody.find('tr').map(...) 組成 JSON 送後端。clusterize.js。aria-label="刪除第 n 列"。$newRow.find('td:first').focus() 讓鍵盤用戶直接輸入。confirm() 或 Modal 確認對話框。掌握這套模式,您就能快速構建功能完整、體驗良好的動態表格元件。