part1:点击全选框,下面的小选框全部选中,再次点击全部取消选中
part2:下面小选框全部选中时,全选框自动选中,否则不选中
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
table {
border-collapse: collapse;
border-spacing: 0;
border: 1px solid #c0c0c0;
width: 500px;
margin: 100px auto;
text-align: center;
}
th {
background-color: #09c;
font: bold 16px "微软雅黑";
color: #fff;
height: 24px;
}
td {
border: 1px solid #d0d0d0;
color: #404060;
padding: 10px;
}
.allCheck {
width: 80px;
}
</style>
</head>
<body>
<table>
<tr>
<th class="allCheck">
<input type="checkbox" name="" id="checkAll"> <span class="all">全选</span>
</th>
<th>商品</th>
<th>商家</th>
<th>价格</th>
</tr>
<tr>
<td>
<input type="checkbox" name="check" class="ck">
</td>
<td>小米手机</td>
<td>小米</td>
<td>¥1999</td>
</tr>
<tr>
<td>
<input type="checkbox" name="check" class="ck">
</td>
<td>小米净水器</td>
<td>小米</td>
<td>¥4999</td>
</tr>
<tr>
<td>
<input type="checkbox" name="check" class="ck">
</td>
<td>小米电视</td>
<td>小米</td>
<td>¥5999</td>
</tr>
</table>
<script>
// 1.点击全选下面的每一项全选中
const checkAll = document.querySelector('#checkAll')
const cks = document.querySelectorAll('.ck')
checkAll.addEventListener('click', function () {
// 点击全选全选中,取消全选,全部取消选中
for (let i = 0; i < cks.length; i++) {
cks[i].checked = checkAll.checked
}
})
//2.小选框判断选中个数,全部选中时则全选按钮也选中
for (let i = 0; i < cks.length; i++) {
const n = 0
cks[i].addEventListener('click', function () {
//获取类名为.ck的有checked属性的,结果为伪数组。再计算这个伪数组长度
const checkedNum = document.querySelectorAll('.ck:checked').length
checkAll.checked = checkedNum === cks.length
})
}
</script>
</body>
</html>