版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LOVE_HopeOne/article/details/76548641
HTML部分
<body>
<input type="checkbox" name="fu">全选(父)<br>
<input type="checkbox" name="zi">子1<br>
<input type="checkbox" name="zi">子2<br>
<input type="checkbox" name="zi">子3<
</body>
全选 和 全不选
$(document).ready(function () {
$("input[name='fu']").click(function () {
var a=$("input[name='fu']").length;
var b=$("input[name='fu']:checked").length;
if (a==b){
$(":checkbox[name='zi']").prop("checked", true);
}else {
$(":checkbox[name='zi']").prop("checked", false);
}
});
});
$(document).ready(function () {
$("input[name='fu']").click(function () {
var a=$("input[name='fu']").length;
var b=$("input[name='fu']:checked").length;
if (a==b){
$(":checkbox[name='zi']").prop("checked", true);
}else {
$(":checkbox[name='zi']").prop("checked", false);
}
});
});
设置 每个子复选框 的name 都为 “zi”,然后设置唯一的全选的复选框的name 为“fu”,然后在文件加载完,这个大前提下,设置全选框的点击事件
反选问题(点击全部的子复选框,选中全选框)
$(document).ready(function () {
$("input[name='zi']").click(function () {
var a=$("input[name='zi']").length;
var b=$("input[name='zi']:checked").length;
if(a>b){
$(":checkbox[name='fu']").prop("checked", false);
}
else if(a==b){
$(":checkbox[name='fu']").prop("checked", true);
}
});
});
}
else if(a==b){
$(":checkbox[name='fu']").prop("checked", true);
}
});
});
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>复选框Demo</title>
<script src="jquery-1.9.1.js"></script>
<script>
$(document).ready(function () {
$("input[name='zi']").click(function () {
var a=$("input[name='zi']").length;
var b=$("input[name='zi']:checked").length;
if(a>b){
$(":checkbox[name='fu']").prop("checked", false);
}
else if(a==b){
$(":checkbox[name='fu']").prop("checked", true);
}
});
$("input[name='fu']").click(function () {
var a=$("input[name='fu']").length;
var b=$("input[name='fu']:checked").length;
if (a==b){
$(":checkbox[name='zi']").prop("checked", true);
}else {
$(":checkbox[name='zi']").prop("checked", false);
}
});
});
</script>
</head>
<body>
<input type="checkbox" name="fu">全选(父)<br>
<input type="checkbox" name="zi">子1<br>
<input type="checkbox" name="zi">子2<br>
<input type="checkbox" name="zi">子3
</body>
</html>