【发布时间】:2022-11-29 07:40:17
【问题描述】:
我需要单独遍历(使用 javascript)每个表行的部分。这意味着我需要先遍历 THEAD 行,然后是 TBODY 行,最后是 TFOOT 行。
我需要做的事情比仅仅为方框着色要复杂得多,但出于本示例的目的,我只是尝试将 thead 行着色为红色,将 tbody 行着色为绿色,将 tfoot 行着色为黄色。如果我能让这些循环为每个部分的行工作,我就可以从那里接手完成其余的编码。
我试过下面的但它不起作用(它告诉我“行未定义”)。有人可以修复 ColorBoxes() 函数代码来让它工作吗?请不要在这里给我 CSS 答案,因为那不能解决问题——我需要遍历每个部分的行。谢谢!
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
<script language='javascript'>
function ColorBoxes()
{
var tbl = document.getElementById('MyTable');
for (var nRow = 0; nRow < tbl.tHead[0].rows; nRow++)
{
tbl.tHead[0].row[nRow].style.backgroundColor = 'red';
}
for (var nRow = 0; nRow < tbl.tBody[0].rows; nRow++)
{
tbl.tBody[0].row[nRow].style.backgroundColor = 'green';
}
for (var nRow = 0; nRow < tbl.tFoot[0].rows; nRow++)
{
tbl.tFoot[0].row[nRow].style.backgroundColor = 'yellow';
}
}
</script>
</head>
<body onLoad='ColorBoxes()'>
<h1>The thead, tbody, and tfoot elements</h1>
<table id='MyTable'>
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<th>Name</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
</table>
</body>
</html>
【问题讨论】:
-
.rows属性是行的集合,而不是数字。
标签: javascript