【发布时间】:2020-08-14 04:59:57
【问题描述】:
我有一个表格,我想在其中选择整行(更改背景颜色)。按复选框选择行,并选择下一行时,前一行必须取消选择。
这是我的桌子
<table id="table" border="1">
<tr>
<th></th>
<th>ID</th>
<th>Name</th>
<th>Surname</th>
</tr>
<tr>
<td class='row'>
<input type='checkbox' class='check' onclick='markRow(0)'>
</td>
<td class='row'>-</td>
<td class='row'>-</td>
<td class='row'>-</td>
</tr>
<tr>
<td class='row'>
<input type='checkbox' class='check' onclick='markRow(1)'>
</td>
<td class='row'>-</td>
<td class='row'>-</td>
<td class='row'>-</td>
</tr>
<tr>
<td class='row'>
<input type='checkbox' class='check' onclick='markRow(2)'>
</td>
<td class='row'>-</td>
<td class='row'>-</td>
<td class='row'>-</td>
</tr>
</table>
#table{
border-collapse: collapse;
}
我将每个表格单元格命名为 class="row"。计算定位特定行的间隔并使用 for 循环,我应该能够为这些表格单元格设置背景颜色。间隔是:第一行是 0-3,第二行是 4-7,第三行是 8-11。
我试过了:
var clear1 = 0;
var clear2 = 0;
//these two should clear the previous row
var counter = 0;
//this will ensure that clearing doesn't happen the first time
//function parameter is given by this checkbox from table
//<input type='checkbox' class='check'onclick='markRow(0)'>
function markRow(rowNumber){
var row = document.getElementsByClassName('row');
var checkboxes = document.getElementsByClassName('check');
var interval = rowNumber*4;
for(var i=interval;i<=interval+3;i++){
row[i].style = "background-color: dodgerblue;";
}
//for example if function gets parameter rowNumber=2, then it will color the cells in interval 8-11
counter++;
if(counter>1){
for(var i=clear1;i<=clear2;i++){
row[i].style = "";
}
checkboxes[clear1].checked = false;
}
clear1 = interval;
clear2 = interval+3;
//these two will save the interval from the current row and next time, for loop will delete style
//using this interval
}
它适用于第一行,但第二行和第三行有时不会检查并且不会被取消选择。我不知道可能是什么问题。
【问题讨论】:
标签: javascript html checkbox html-table row