我想在单击任何子项时选择父项。这段代码正在检查和检查。
$(function() {
$(".child").on("click",function() {
$parent = $(this).prevAll(".parent");
if ($(this).is(":checked")) $parent.prop("checked",true);
else {
var len = $(this).parent().find(".child:checked").length;
$parent.prop("checked",len>0);
}
});
$(".parent").on("click",function() {
$(this).parent().find(".child").prop("checked",this.checked);
});
});
它正在处理输入(请参阅link http://jsfiddle.net/fEWaH/)
<input type='checkbox' name='cat' class='parent' value='cat1' />Category 1<br>
<input type='checkbox' name='foo' class='child' value='1' />SubCategory 1<br>
<input type='checkbox' name='foo' class='child' value='1' />SubCategory 2
但使用
检查不起作用(请参阅此link http://jsfiddle.net/dR84e/)
<input type='checkbox' name='cat' class='parent' value='cat1' />Category 1
<ul>
<il><input type='checkbox' name='foo' class='child' value='1' />SubCategory 1</il>
<il><input type='checkbox' name='foo' class='child' value='1' />SubCategory 2</il>
</ul>
查看您的代码后,我提出了一个我认为您想要的解决方案。
通过使用自定义属性,如果选择了子复选框之一,我就选择了顶级复选框。如果至少选中了一个子级别复选框,则父级别将保持选中状态。否则,未经检查。这可能比浏览 DOM 更容易,并且最终代码要少得多。
$(function() {
$(".child").change(function() {
if ($('.child[thisparent=' + $(this).attr('thisparent') + ']:checked').length == 0) {
$('#' + $(this).attr('thisparent')).prop('checked', false);
}
else {
$('#' + $(this).attr('thisparent')).prop('checked', true);
}
});
$(".parent").change(function() {
$('input[thisparent="' + $(this).attr('id') + '"]').prop('checked', $(this).prop('checked'));
});
});
JSFiddle:here http://jsfiddle.net/dR84e/8/
另外,你的html无效。你的“il”标签应该是“li”
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)