我一直在寻找一个"完整"的解决方案来嵌套父子复选框,它可以根据层次结构正确地改变状态.
大多数"解决方案"不起作用或仅适用于一个级别.它们还要求您以特定方式命名复选框.
这个 Stack Overflow讨论涵盖了要点,但也提供了Rory 在这里发现的一个很好的解决方案.
我在我的开发项目中测试了它,它完全独立运行.但是,我使用的是Bootstrap 2.x和复选框
我有一个JSFiddle,它显示了工作示例代码,然后是我的版本,带有禁用的父复选框,然后是不起作用的bootsrap代码版本.
Raw working example
$(function () {
// Apparently click is better chan change? Cuz IE?
$('input[type="checkbox"]').change(function (e) {
var checked = $(this).prop("checked"),
container = $(this).parent(),
siblings = container.siblings();
container.find('input[type="checkbox"]').prop({
indeterminate: false,
checked: checked
});
function checkSiblings(el) {
var parent = el.parent().parent(),
all = true;
el.siblings().each(function () {
return all = ($(this).children('input[type="checkbox"]').prop("checked") === checked);
});
if (all && checked) {
parent.children('input[type="checkbox"]').prop({
indeterminate: false,
checked: checked
});
checkSiblings(parent);
} else if (all && !checked) {
parent.children('input[type="checkbox"]').prop("checked", checked);
parent.children('input[type="checkbox"]').prop("indeterminate", (parent.find('input[type="checkbox"]:checked').length > 0));
checkSiblings(parent);
} else {
el.parents("li").children('input[type="checkbox"]').prop({
indeterminate: true,
checked: false
});
}
}
checkSiblings(container);
});
});
我的理解是代码需要在某处改变以使用父母或最近的代码.更好的代码可以帮助确定需要进行更改的位置以使Bootstrap版本正常工作.