動態生成的表格行 <tr>,綁定點擊事件欲刪除整行,嘗試 $(this).remove()、deleteRow 均無效。
<a> 或 <td>,$(this) 指向該元素,而非 tr。a → td → tr,需向上查找兩層父元素。$(table).on('click', 'a', handler)。function removeTr(el) {
// el 為點擊的 或
var td = el.tagName === 'TD' ? el : el.parentNode; // 確保拿到 td
var tr = td.parentNode; // td 的父節點是 tr
tr.parentNode.removeChild(tr); // 從 tbody 移除 tr
}
// HTML
// 刪除
// 或 ...
// 1. 靜態綁定(行已存在)
$('table').on('click', '.delete-btn', function() {
$(this).closest('tr').remove(); // closest 向上查找最近的 tr
});
// 2. 動態添加行後同樣生效(委派給不動的祖先,如 table 或 tbody)
$('#data-table').on('click', '.delete-btn', function() {
$(this).closest('tr').remove();
});
// 3. 如果綁在 tr 上
$('#data-table').on('click', 'tr', function() {
$(this).remove(); // this 就是 tr
});
| 方法 | 說明 | 適用場景 |
|---|---|---|
.parent() | 獲取直接父元素(單層) | 結構固定、層級已知 |
.parents('selector') | 獲取所有祖先元素,可篩選 | 需匹配特定祖先 |
.closest('selector') | 從自身開始向上查找最近匹配祖先(含自身) | 最推薦,結構變動健壯 |
.remove() | 從 DOM 移除元素及其子孫,清理事件/數據 | 完全刪除 |
.detach() | 移除但保留 jQuery 數據/事件,可重新插入 | 暫時移除後復用 |
element.remove() | 原生 DOM API(現代瀏覽器支援) | 無 jQuery 依賴 |
<table id="data-table">
<thead><tr><th>名稱</th><th>操作</th></tr></thead>
<tbody></tbody>
</table>
<button id="add-row">添加行</button>
<script>
$('#add-row').click(function() {
var idx = $('#data-table tbody tr').length + 1;
$('#data-table tbody').append(
'<tr><td>項目 ' + idx + '</td>' +
'<td><button class="delete-btn">刪除</button></td></tr>'
);
});
// 事件委派:針對動態 .delete-btn 生效
$('#data-table').on('click', '.delete-btn', function() {
$(this).closest('tr').remove();
});
</script>
移除動態 tr 核心在於:事件委派給靜態祖先 + .closest('tr') 精準定位行。避免直接綁定在動態元素上,避免硬編碼 .parent().parent() 這類脆弱的層級依賴。