分析:
1、全选和取消全选:让下方所有复选框的checked属性(选中状态)跟随全选按钮
2、下方的所有复选框选中全选按钮才选中,其中一个不选中全选按钮都不选中
每次点击下面的某个复选框都要循环检查下方复选框是否都被选中
flag保存全选按钮的选中状态
HTML结构:
<table border="1" cellspacing="" cellpadding="0">
<tr>
<th><input type="checkbox" id="selectAll"/>全选</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>张三</td>
<td>男</td>
<td>20</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>张三1</td>
<td>男</td>
<td>20</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>张三2</td>
<td>男</td>
<td>20</td>
</tr>
</table>
JS:
<script type="text/javascript">
// 获取单元格中的input
let inputList=document.querySelectorAll('table tr td input')
// 为全选绑定点击事件
selectAll.addEventListener('click',function(){
// 将全选复选框的选中状态保存在status中
let status=this.checked
// 遍历获取到的input
for(let i=0;i<inputList.length;i++){
// 为每个单元格的复选框的checked的属性赋值
inputList[i].checked=status
}
})
for(let i=0;i<inputList.length;i++){
inputList[i].addEventListener('click',function(){
let flag=true
for(let j=0;j<inputList.length;j++){
if(!inputList[j].checked){
flag=false
break
}
}
selectAll.checked=flag
})
}
</script>

本文分析了如何实现HTML表单中的全选和取消全选功能。通过控制全选按钮的checked属性来影响所有复选框的状态,并在复选框被点击时动态检查是否所有复选框都已被选中,以保持全选按钮的正确状态。
1352

被折叠的 条评论
为什么被折叠?



