效果图:
案例代码:
<!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>Document</title>
<style>
table {
width: 100%;
}
th,
td {
border: 1px solid black;
text-align: center;
}
</style>
</head>
<body>
<table>
<thead>
<th><input type="checkbox" name="allSel" id="allSel"></th>
<th>学号</th>
<th>姓名</th>
<th>班级</th>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="selItem"></td>
<td>01</td>
<td>小张</td>
<td>1班</td>
</tr>
<tr>
<td><input type="checkbox" class="selItem"></td>
<td>02</td>
<td>小李</td>
<td>2班</td>
</tr>
<tr>
<td><input type="checkbox" class="selItem"></td>
<td>03</td>
<td>小王</td>
<td>1班</td>
</tr>
</tbody>
<button id="btnFan">反选</button>
<button id="btnAll">全选</button>
</table>
<script src="./js/jquery-3.6.0.js"></script>
<script type="text/javascript">
(function($) {
$("#allSel").click(function() {
//获取全选框的状态
let nowState = $("#allSel").prop("checked");
//改变其他选项的状态
$(".selItem").prop("checked", nowState);
})
//判断所有的行中,checkbox的状态,是否为全部选中
function checkAllChecked() {
if ($(".selItem:not(:checked)").length == 0) {
$("#allSel").prop("checked", true);
} else {
$("#allSel").prop("checked", false);
}
}
//给checkbox添加点击事件
$(".selItem").click(function() {
checkAllChecked();
})
//添加反选的点击事件
$("#btnFan").click(function() {
let allCheckBox = $(".selItem");
for (let i = 0; i < allCheckBox.length; i++) {
allCheckBox[i].checked = !allCheckBox[i].checked;
}
checkAllChecked();
})
//添加全选的点击事件
$("#btnAll").click(function() {
$(".selItem").prop("checked", true);
$("#allSel").prop("checked", true);
})
})(jQuery);
</script>
</body>
</html>