示例代码:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>全选反选取消测试</title>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script type="text/javascript">
//全选、取消全选的事件
function selectAll(){
console.log(1);
console.log($("#checkall").prop("checked"));
if ($("#checkall").prop("checked")) {
console.log(2);
$("input[type='checkbox'][name='checkedres']").prop("checked",true);//全选
} else {
console.log(3);
$("input[type='checkbox'][name='checkedres']").prop("checked",false); //取消全选
}
}
//子复选框的事件
function setSelectAll(){
//当没有选中某个子复选框时,SelectAll取消选中
if (!$(".checkedres").checked) {
$("#checkall").prop("checked", false);
}
var chsub = $("input[type='checkbox'][name='checkedres']").length; //获取subcheck的个数
var checkedsub = $("input[type='checkbox'][name='checkedres']:checked").length; //获取选中的subcheck的个数
if (checkedsub == chsub) {
$("#checkall").prop("checked", true);
}
}
</script>
</head>
<body>
<input id="checkall" name="checkall" type="checkbox" onclick="selectAll()"/>全选
//设置子复选框
<input class="checkedres" name="checkedres" type="checkbox" onclick="setSelectAll()"/>item 1
<input class="checkedres" name="checkedres" type="checkbox" onclick="setSelectAll()"/>item 2
<input class="checkedres" name="checkedres" type="checkbox" onclick="setSelectAll()"/>item 3
<input class="checkedres" name="checkedres" type="checkbox" onclick="setSelectAll()"/>item 4
</body>
</html>
复制黏贴运行即可看效果