在網頁中透過 JavaScript 讀取/修改 <table> 指定列、欄的儲存格內容。
table.rows[index]:取得 HTMLTableRowElement 集合。row.cells[index]:取得 HTMLTableCellElement 集合。cell.innerHTML / cell.textContent:讀寫內容。<table id="myTable" border="1">
<tr><td>1,1</td><td>1,2</td><td>1,3</td></tr>
<tr><td>2,1</td><td>2,2</td><td>2,3</td></tr>
<tr><td>3,1</td><td>3,2</td><td>3,3</td></tr>
</table>
<br>
<input type="text" id="inputText" placeholder="新內容">
<button onclick="updateCell(2, 2)">修改第3列第3欄 (0-based)</button>
<script>
function updateCell(rowIdx, colIdx) {
const table = document.getElementById('myTable');
const newValue = document.getElementById('inputText').value;
if (table.rows[rowIdx] && table.rows[rowIdx].cells[colIdx]) {
table.rows[rowIdx].cells[colIdx].textContent = newValue;
} else {
alert('索引超出範圍');
}
}
// 讀取範例
function readCell(rowIdx, colIdx) {
const table = document.getElementById('myTable');
return table.rows[rowIdx]?.cells[colIdx]?.textContent || '';
}
</script>
// 新增列
const newRow = table.insertRow(-1); // -1 為末尾
newRow.insertCell(0).textContent = '新資料1';
newRow.insertCell(1).textContent = '新資料2';
// 刪除列
table.deleteRow(1); // 刪除第 2 列
for (const row of table.rows) {
for (const cell of row.cells) {
console.log(cell.textContent);
}
}
table.addEventListener('click', (e) => {
const td = e.target.closest('td');
if (td) {
const rowIdx = td.parentElement.rowIndex;
const colIdx = td.cellIndex;
console.log(`點擊: 第${rowIdx+1}列, 第${colIdx+1}欄 = ${td.textContent}`);
}
});
thead/tbody/tfoot 會影響 rows 集合順序,建議用 table.querySelectorAll('tbody tr') 精確控制。colspan/rowspan) 會導致 cells 索引與視覺欄位不符,需額外計算。掌握 HTMLTableElement DOM 介面,即可靈活操作表格資料。