Javascript 复选框单击全部
我想在单击任何子项时选择父项。此代码正在工作,检查和检查Javascript 复选框单击全部,javascript,Javascript,我想在单击任何子项时选择父项。此代码正在工作,检查和检查 $(function() { $(".child").on("click",function() { $parent = $(this).prevAll(".parent"); if ($(this).is(":checked")) $parent.prop("checked",true); else { var len = $(this).parent().find(".chil
$(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);
});
});
它与输入一起工作(参见此)
类别1
子类别1
子类别2
但是使用1类
子类别1
子类别2
添加无序列表会添加另一层父子关系。编辑此行:
$parent = $(this).parent().prevAll(".parent");
为此:
$parent = $(this).parent().parent().prevAll(".parent");
正确地指向您的目标家长。在查看了您的代码后,我想出了一个我认为您想要的解决方案 通过使用自定义属性,如果选中了其中一个子复选框,我就选中了顶层复选框。如果至少选中了一个子级别复选框,则父级别将保持选中状态。否则,未经检查。这可能比在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:
此外,您的html是无效的。你的“il”标签应该是“li”如果你想知道答案,你应该真正显示你的代码,链接你的小提琴,并更好地解释你的问题。请参阅链接以了解问题这就是我想要的,非常感谢你的帮助
$parent = $(this).parent().parent().prevAll(".parent");
$(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'));
});
});