最近项目中前台经常遇到如下需求:
1:用户勾选父类checkbox框,关联的子类checkbox框被自动勾选上
2:当子类的所有checkbox框全部被勾选,父类的checkbox也被勾选
这就是最普遍的checkbox级联勾选的问题
index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Web Project</title>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script type="text/javascript" src="jquery-check-1.0.js"></script>
</head>
<body>
p:<input type="checkbox" check-group="genre"/><br>
c:<input type="checkbox" check-child="genre"/> <input type="checkbox" check-child="genre"/> <input type="checkbox" check-child="genre"/> <br>
p:<input type="checkbox" check-group="genre1"/><br>
c:<input type="checkbox" check-child="genre1"/> <input type="checkbox" check-child="genre1"/> <input type="checkbox" check-child="genre1"/>
</body>
</html>
jquery-check-1.0.js
/**
*checkbox框全选1.0版,基于jQuery
* 适用浏览器IE8,9,10,11 firefox chrome
* 适用方法 页面父checkbox添加属性check-group,其子类checkbox框增加属性check-child
* 两个属性的值相等即可完成级联关联
*/
$(function() {
$(":input[check-group]").each(function() {
var checkbox = $(this);
pName = checkbox["0"].attributes["check-group"].value;
plugin(pName);
});
});
var plugin = function(team) {
$(":input[check-group=" + team + "]").click(function() {
checkAll(team);
});
$(":input[check-child=" + team + "]").click(function() {
checkparent(team);
});
};
function checkAll(team) {
var pName;
var pcheck;
$(":input[check-group=" + team + "]").each(function() {
var checkbox = $(this);
pName = checkbox["0"].attributes["check-group"].value;
pcheck = checkbox["0"].checked;
});
$(":input[check-child=" + team + "]").each(function() {
var checkbox = $(this);
var childName = checkbox["0"].attributes["check-child"].value;
if (pName == childName) {
if (pcheck == true)
checkbox["0"].checked = true;
else
checkbox["0"].checked = false;
}
});
};
function checkparent(team) {
var total = $(":input[check-child=" + team + "]").length;
var checkedSize = 0;
var childName;
$(":input[check-child=" + team + "]").each(function() {
var checkbox = $(this);
childName = checkbox["0"].attributes["check-child"].value;
if (checkbox["0"].checked == true) {
checkedSize++;
}
});
if (checkedSize == total) {
$(":input[check-group=" + childName + "]")[0].checked = true;
} else {
$(":input[check-group=" + childName + "]")[0].checked = false;
}
};
希望有大神改进或者提供更好的解决方案~