全选反选
程序员文章站
2022-06-01 13:15:30
...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>全选反选</title>
<style>
* {
padding: 0;
margin: 0;
}
.wrap {
width: 300px;
margin: 100px auto;
}
table {
border-collapse: collapse;
border-spacing: 0;
border: 1px solid black;
width: 300px;
}
th,
td {
border: 1px solid rgb(53, 52, 52);
color: black;
padding: 10px;
}
th {
background-color: rgb(252, 215, 147);
font: bold 16px "微软雅黑";
color: #fff;
}
td {
font: 14px "微软雅黑";
}
tbody {
text-align: center;
}
tbody tr {
background-color: #f0f0f0;
}
tbody tr:hover {
cursor: pointer;
background-color: #fafafa;
}
</style>
</head>
<body>
<div class="wrap">
<table>
<thead>
<tr>
<th>
<input type="checkbox" id="checkAll" />
</th>
<th>商品</th>
<th>价钱</th>
</tr>
</thead>
<tbody id="checkTb">
<tr>
<td>
<input type="checkbox" />
</td>
<td>键盘</td>
<td>400</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>电脑</td>
<td>5000</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>鼠标</td>
<td>50</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>路由器</td>
<td>200</td>
</tr>
</tbody>
</table>
<input type="button" value="反选" id="btn" />
</div>
<script>
//1.全选
//1.1 获取父checkbox,注册点击事件
var checkAll = document.getElementById("checkAll");
var checkTb = document.getElementById("checkTb");
var inputs = checkTb.getElementsByTagName("input");
checkAll.onclick = function() {
//1.2 找到所有子的checkbox,让这些checkbox的状态和父checkbox保持一致
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if (input.type == "checkbox") {
input.checked = this.checked;
}
}
}
//2.当点击子checkbox,如果所有的子checkbox都被选中,父checkbox也选中
//如果有一个子checkbox没有被选中,父checkbox也不选中
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
//判断是否是checkbox
if (input.type != "checkbox") {
//结束当前循环,继续下一次循环
continue;
}
//给子checkbox注册点击事件
input.onclick = function() {
checkAllBox();
}
}
//判断父checkbox的状态 封装函数
function checkAllBox() {
//假设所有的子checkbox都被选中
var isAllChecked = true;
//判断是否所有的子checkbox都被选中
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
//判断是否是checkbox
if (input.type != "checkbox") {
//结束当前循环,继续下一次循环
continue;
}
if (!input.checked) {
isAllChecked = false;
}
}
checkAll.checked = isAllChecked
}
//3.反选
//3.1给反选按钮注册点击事件
var btn = document.getElementById("btn");
btn.onclick = function() {
//3.2找到所有的子checkbox,让其反选
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if (input.type != "checkbox") {
//结束当前循环,继续下一次循环
continue;
}
//让子checkbox反选
input.checked = !input.checked;
//设置父checkbox的状态
checkAllBox();
}
}
</script>
</body>
</html>
上一篇: 全选,反选,取消全选