在 web 前端开发中,表格是一种常见的展示数据的方式。表格由行和列组成,每个单元格称为一个表格单元格(table cell)。在处理表格数据时,我们经常需要对表格中的单元格进行操作,比如读取单元格的内容、修改单元格的样式等。在本文中,我们将介绍如何使用 JavaScript 操作表格单元格的集合。
获取表格单元格集合
要操作表格单元格,首先需要获取表格元素。我们可以使用 document.getElementById 或 document.querySelector 方法来获取表格元素,然后通过 rows 和 cells 属性来获取行和单元格的集合。
示例代码:
// www.javascriptcn.com code example
<table id="myTable">
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
</tr>
<tr>
<td>Row 2, Cell 1</td>
<td>Row 2, Cell 2</td>
</tr>
</table>
<script>
const table = document.getElementById('myTable');
const rows = table.rows;
const cells = rows[0].cells;
console.log(cells[0].innerText); // 输出:Row 1, Cell 1
</script>在上面的示例中,我们首先获取了 id 为 myTable 的表格元素,然后通过 rows 属性获取了表格的行集合,再通过 cells 属性获取了第一行的单元格集合。最后,我们通过 innerText 属性获取了第一个单元格的内容并输出。
操作表格单元格
一旦我们获取了表格单元格的集合,就可以对单元格进行各种操作,比如修改内容、样式等。
示例代码:
// www.javascriptcn.com code example
<table id="myTable">
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
</tr>
<tr>
<td>Row 2, Cell 1</td>
<td>Row 2, Cell 2</td>
</tr>
</table>
<script>
const table = document.getElementById('myTable');
const rows = table.rows;
const cells = rows[0].cells;
cells[0].innerText = 'New Content';
cells[0].style.backgroundColor = 'lightblue';
</script>在上面的示例中,我们将第一个单元格的内容修改为 New Content,并将背景色设置为 lightblue。
遍历表格单元格
有时候我们需要遍历整个表格的所有单元格,可以使用嵌套循环来实现。
示例代码:
// www.javascriptcn.com code example
<table id="myTable">
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
</tr>
<tr>
<td>Row 2, Cell 1</td>
<td>Row 2, Cell 2</td>
</tr>
</table>
<script>
const table = document.getElementById('myTable');
const rows = table.rows;
for (let i = 0; i < rows.length; i++) {
const cells = rows[i].cells;
for (let j = 0; j < cells.length; j++) {
console.log(cells[j].innerText);
}
}
</script>在上面的示例中,我们使用嵌套循环遍历了整个表格,并输出了每个单元格的内容。
通过这篇文章,你应该已经掌握了如何使用 JavaScript 操作表格单元格的集合。