<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>表单全选与取消选择</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<style>
#formChoose {
font-size: 18px;
font-family: '宋体';
margin-top: 50px;
}
h2 {
text-align: center;
color: lightblue;
}
h2:hover {
color: pink;
}
th {
background-color: azure;
}
table,
th {
text-align: center;
}
/* table悬浮整行 */
/* tbody tr:hover td{cursor:pointer;background-color: antiquewhite;} */
.q:hover{cursor:pointer;background-color: antiquewhite;}
</style>
</head>
<body>
<div id="formChoose">
<h2>表单全选与取消选择</h2>
<table class="table table-bordered">
<thead>
<tr>
<th>
<input type="checkbox" name="全选" id="allChoose">
</th>
<th>姓名</th>
<th>职位</th>
<th>部门</th>
</tr>
</thead>
<tbody>
<tr class="q">
<td>
<input type="checkbox" name="单选">
</td>
<td>小白</td>
<td>Web前端实习</td>
<td>综合部</td>
</tr>
<tr class="q">
<td>
<input type="checkbox" name="单选">
</td>
<td>小柒</td>
<td>Java开发</td>
<td>综合部</td>
</tr>
<tr class="q">
<td>
<input type="checkbox" name="单选">
</td>
<td>小寒</td>
<td>HR</td>
<td>人事部</td>
</tr>
</tbody>
</table>
</div>
<script>
//表单全选、取消全选,循环让checked属性跟随复选框即可
var all = document.getElementById('allChoose')
var tbInput = document.querySelector('tbody').getElementsByTagName('input')
all.onclick = function(){
//console.log(this.checked) 输出true或false
for(i=0;i<tbInput.length;i++){
tbInput[i].checked = this.checked;
}
}
//为下面的小复选框注册事件,当全部选中时,总复选框也选中,当其中有一个么选中时,复选框取消选中
for(i=0;i<tbInput.length;i++){
tbInput[i].onclick = function(){
var flag = true; // flag控制全选按钮是否选中
//检查所有的小复选框的选中状态
for (var i=0;i<tbInput.length;i++){
if(!tbInput[i].checked){ // 如果有一个么有选中,flag=false,且break退出
flag = false;
break;
}
}
all.checked = flag;
}
}
</script>
</body>
</html>
表单全选与取消选择
于 2022-04-01 16:06:10 首次发布