创建一个表格,用js对一个表格实现全选和全取消功能
时间: 2023-04-04 14:00:25 浏览: 102
javascript实现可全选、反选及删除表格的方法
可以使用以下代码实现:
HTML代码:
<table>
<thead>
<tr>
<th><input type="checkbox" id="checkAll"></th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkItem"></td>
<td>张三</td>
<td>20</td>
<td>男</td>
</tr>
<tr>
<td><input type="checkbox" class="checkItem"></td>
<td>李四</td>
<td>25</td>
<td>女</td>
</tr>
<tr>
<td><input type="checkbox" class="checkItem"></td>
<td>王五</td>
<td>30</td>
<td>男</td>
</tr>
</tbody>
</table>
JS代码:
var checkAll = document.getElementById('checkAll');
var checkItems = document.getElementsByClassName('checkItem');
checkAll.addEventListener('click', function() {
for (var i = ; i < checkItems.length; i++) {
checkItems[i].checked = this.checked;
}
});
for (var i = ; i < checkItems.length; i++) {
checkItems[i].addEventListener('click', function() {
var checkedCount = ;
for (var j = ; j < checkItems.length; j++) {
if (checkItems[j].checked) {
checkedCount++;
}
}
checkAll.checked = checkedCount === checkItems.length;
});
}
阅读全文