基于jquery的checkbox的全选自定义标签插件
最近项目中前台经常遇到如下需求:
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; } };
希望有大神改进或者提供更好的解决方案~
相关推荐
EdwardSiCong 2020-11-23
85477104 2020-11-17
hhanbj 2020-11-17
81427005 2020-11-11
seoppt 2020-09-13
honeyth 2020-09-13
WRITEFORSHARE 2020-09-13
84483065 2020-09-11
momode 2020-09-11
85477104 2020-08-15
83510998 2020-08-08
82550495 2020-08-03
tthappyer 2020-08-03
84901334 2020-07-28
tthappyer 2020-07-25
TONIYH 2020-07-22
tztzyzyz 2020-07-20
83510998 2020-07-18
81463166 2020-07-17