在前端開發中,通過 JavaScript 動態生成 HTML 表格後,常需根據用戶交互「關閉」表格。此處的「關閉」通常包含兩種語義:**隱藏** 或 **從 DOM 中移除**。兩者差異巨大,需按業務場景選擇。
保留 DOM 節點與事件綁定,僅切換可見性。
// 隱藏
tableElement.style.display = 'none';
// 或
tableElement.hidden = true;
// 顯示
tableElement.style.display = 'table'; // 表格專用 display 值
tableElement.hidden = false;
從 DOM 樹中移除,若無其他引用,垃圾回收器將回收內存。
// 原生 JS
tableElement.remove(); // 現代瀏覽器支持
// 或兼容寫法
if (tableElement.parentNode) {
tableElement.parentNode.removeChild(tableElement);
}
// jQuery(若項目引用)
$('#tableId').remove(); // 同時清理數據與事件
<button id="createBtn">創建表格</button>
<button id="hideBtn">隱藏表格</button>
<button id="removeBtn">刪除表格</button>
<div id="container"></div>
<script>
let table = null;
document.getElementById('createBtn').onclick = () => {
if (table) return; // 防止重複創建
table = document.createElement('table');
table.id = 'dynamicTable';
table.border = '1';
table.innerHTML = '<tr><th>姓名</th><th>年齡</th></tr><tr><td>張三</td><td>25</td></tr>';
document.getElementById('container').appendChild(table);
};
document.getElementById('hideBtn').onclick = () => {
if (table) table.style.display = 'none';
};
document.getElementById('removeBtn').onclick = () => {
if (table) {
table.remove();
table = null; // 斷開引用,利於 GC
}
};
</script>
table 或 container 上,避免逐行綁定且移除時避免內存洩漏。transition: opacity 0.3s,配合 opacity: 0 再 display: none,體驗更平滑。