<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>動態表格操作演示</title>
<style>
table { border-collapse: collapse; width: 100%; max-width: 600px; margin: 1rem auto; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background: #333; color: #fff; }
tbody tr:nth-child(odd) { background: #ffffee; }
tbody tr:nth-child(even) { background: #fff38f; }
.btn { padding: 4px 12px; margin: 0 2px; cursor: pointer; }
.btn-danger { background: #dc3545; color: white; border: none; border-radius: 3px; }
.btn-primary { background: #007bff; color: white; border: none; border-radius: 3px; }
</style>
</head>
<body>
<div style="text-align:center; margin-bottom:1rem;">
<button id="addRow" class="btn btn-primary">+ 添加行</button>
<button id="resetTable" class="btn">重置表格</button>
</div>
<table id="dataTable">
<thead>
<tr><th>#</th><th>名稱</th><th>操作</th></tr>
</thead>
<tbody></tbody>
</table>
<script>
// 狀態管理
let rowCounter = 0;
const $tbody = $('#dataTable tbody');
// 初始化 5 行演示數據
function initTable(count = 5) {
$tbody.empty();
rowCounter = 0;
for (let i = 0; i < count; i++) addRow(`初始項目 ${i+1}`);
updateStriping();
}
// 添加行
function addRow(name = `新項目 ${++rowCounter}`) {
const $row = $(`
<tr>
<td>${rowCounter}</td>
<td>${name}</td>
<td>
<button class="btn btn-danger delete-btn">刪除</button>
<button class="btn btn-primary edit-btn">編輯</button>
</td>
</tr>
`);
$tbody.append($row);
updateStriping();
}
// 刪除行(事件委託)
$tbody.on('click', '.delete-btn', function() {
$(this).closest('tr').remove();
updateStriping();
resequence();
});
// 編輯行(示例:雙擊單元格編輯)
$tbody.on('dblclick', 'td:eq(1)', function() {
const $cell = $(this);
const currentText = $cell.text();
const $input = $('').val(currentText).css('width', '100%');
$cell.html($input);
$input.trigger('focus').on('blur keydown', function(e) {
if (e.type === 'blur' || e.key === 'Enter') {
$cell.text($(this).val() || currentText);
}
});
});
// 重新計算序號
function resequence() {
$tbody.find('tr').each(function(i) {
$(this).find('td:first').text(i + 1);
});
}
// 維護斑馬紋
function updateStriping() {
$tbody.find('tr').each(function(i) {
$(this).toggleClass('odd', i % 2 === 0)
.toggleClass('even', i % 2 === 1);
});
}
// 綁定按鈕
$('#addRow').click(() => addRow());
$('#resetTable').click(() => initTable(5));
// 初始化
initTable(5);
</script>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
</body>
</html>
// ❌ 直接綁定:新增行無效
$('.delete-btn').click(...);
// ✅ 委託給靜態父容器:動態元素自動生效
$tbody.on('click', '.delete-btn', function() { ... });
原理:利用事件冒泡,在 tbody 捕獲子元素點擊,匹配選擇器執行處理器。
tr:nth-child(odd/even) —— 純 CSS,無 JS 開銷,**首選方案**.odd/.even 類 —— 兼容舊瀏覽器、需手動維護/* 現代 CSS 方案(推薦) */
tbody tr:nth-child(odd) { background: #ffffee; }
tbody tr:nth-child(even) { background: #fff38f; }
/* 動態增刪後瀏覽器自動重新計算,零代碼維護 */
function resequence() {
$tbody.find('tr').each(function(i) {
$(this).find('td:first').text(i + 1);
});
}
每次增刪後調用,保證序號連續。
const tbody = document.querySelector('#dataTable tbody');
let rowCounter = 0;
function addRow(name = `項目 ${++rowCounter}`) {
const row = tbody.insertRow();
row.innerHTML = `
${rowCounter}
${name}
`;
updateStriping();
}
// 事件委託原生寫法
tbody.addEventListener('click', e => {
const btn = e.target.closest('button');
if (!btn) return;
const row = btn.closest('tr');
if (btn.classList.contains('delete-btn')) {
row.remove();
updateStriping();
resequence();
}
});
function updateStriping() {
[...tbody.rows].forEach((row, i) => {
row.classList.toggle('odd', i % 2 === 0);
row.classList.toggle('even', i % 2 === 1);
});
}
function resequence() {
[...tbody.rows].forEach((row, i) => {
row.cells[0].textContent = i + 1;
});
}
tbody.addEventListener('dblclick', e => {
const cell = e.target.closest('td[data-editable]');
if (!cell) return;
const original = cell.textContent;
const input = document.createElement('input');
input.value = original;
input.style.width = '100%';
cell.textContent = '';
cell.appendChild(input);
input.focus();
const finish = (save) => {
cell.textContent = save ? input.value : original;
cell.removeEventListener('keydown', keydownHandler);
};
const keydownHandler = e => {
if (e.key === 'Enter') finish(true);
if (e.key === 'Escape') finish(false);
};
input.addEventListener('keydown', keydownHandler);
input.addEventListener('blur', () => finish(true), { once: true });
});
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
Sortable.create(document.querySelector('#dataTable tbody'), {
animation: 150,
handle: '.drag-handle', // 拖拽手柄
onEnd: () => { resequence(); updateStriping(); }
});
</script>
動態表格操作的核心模式:
:nth-child 而非 JS 切換類名理解這套模式,無論用 jQuery、Vue、React 還是原生 JS,都能構建健壯的動態表格交互。