表格列勾選後取得該列所有 <td> 內容,是後台管理、資料編輯的基礎操作。本文展示從傳統 DOM 遍歷到現代 closest/querySelectorAll 的演進,並處理動態表格、分頁、虛擬滾動等實戰場景。
function test(checkbox) {
if (!checkbox.checked) return;
var tr = checkbox.parentNode.parentNode; // 假設 checkbox 在 td > tr
var tds = tr.cells; // HTMLCollection,即時動態
var str = 'you click ';
for (var i = 0; i < 3; i++) { // 只取前 3 欄
str += tds[i].innerHTML + '--';
}
alert(str);
}
// HTML
<input type="checkbox" onclick="test(this);" />
缺點:耦合 DOM 結構(parentNode.parentNode)、onclick 內聯難維護、cells 為即時集合效能較差。
<table id="dataTable">
<thead><tr><th><input type="checkbox" id="selectAll"></th><th>ID</th><th>名稱</th><th>狀態</th></tr></thead>
<tbody>
<tr data-id="1"><td><input type="checkbox" class="row-check" value="1"></td><td>1</td><td>產品 A</td><td>上架</td></tr>
<tr data-id="2"><td><input type="checkbox" class="row-check" value="2"></td><td>2</td><td>產品 B</td><td>下架</td></tr>
</tbody>
</table>
<script>
const table = document.getElementById('dataTable');
// 事件代理:單一監聽器處理所有列勾選
table.addEventListener('change', function(e) {
if (!e.target.matches('.row-check')) return;
const checkbox = e.target;
const row = checkbox.closest('tr'); // 向上找最近的 tr,結構變動不怕
if (!row) return;
// 取得該列所有 td 文字內容(排除第一欄 checkbox)
const cells = row.querySelectorAll('td:not(:first-child)');
const rowData = Array.from(cells).map(td => td.textContent.trim());
console.log('Row ID:', row.dataset.id);
console.log('Row Data:', rowData); // ["1", "產品 A", "上架"]
// 同步更新全選狀態
updateSelectAll();
});
function updateSelectAll() {
const all = table.querySelectorAll('.row-check');
const checked = table.querySelectorAll('.row-check:checked');
document.getElementById('selectAll').checked = all.length === checked.length && all.length > 0;
document.getElementById('selectAll').indeterminate = checked.length > 0 && checked.length < all.length;
}
</script>
// 表頭定義欄位 key
const headers = ['id', 'name', 'status'];
table.addEventListener('change', function(e) {
if (!e.target.matches('.row-check')) return;
const row = e.target.closest('tr');
const cells = row.querySelectorAll('td:not(:first-child)');
const rowObj = { id: row.dataset.id }; // 從 data-* 取主鍵
cells.forEach((td, i) => {
rowObj[headers[i]] = td.textContent.trim();
});
console.log(rowObj); // {id: "1", name: "產品 A", status: "上架"}
});
若使用虛擬滾動(如 react-window、Clusterize.js),DOM 中不存在所有列。此時**不可依賴 DOM 遍歷**,必須從**資料源(State/Store)根據 ID 取值**:
// 假設資料存於陣列
const allData = [
{ id: 1, name: '產品 A', status: '上架' },
{ id: 2, name: '產品 B', status: '下架' }
];
// checkbox value 綁定 id
table.addEventListener('change', function(e) {
if (!e.target.matches('.row-check')) return;
const id = Number(e.target.value);
const rowData = allData.find(d => d.id === id);
console.log('從資料源取得:', rowData);
});
$('#dataTable').on('change', '.row-check', function() {
if (!this.checked) return;
const $row = $(this).closest('tr');
const data = {};
$row.find('td:not(:first)').each(function(i) {
data[headers[i]] = $(this).text().trim();
});
console.log(data);
});
closest + querySelectorAll + 事件代理 |
| jQuery 專案 | $(this).closest('tr').find('td') |
| React/Vue/Angular | **不要操作 DOM**,直接從 State/Props 根據 ID 取資料 |
| 虛擬滾動/大數據 | 僅在資料層操作,DOM 只負責渲染可視區 |
核心原則:**資料是單一真相來源,DOM 只是投影**。勾選事件只傳遞 ID,業務邏輯在資料層處理,才能應對複雜場景。