如果选中了父复选框,则单击所有的子复选框。如果单击任何子复选框的,则单击父复选框。我已经编写了代码,但它不能正常工作。当我取消选中子复选框时,尽管单击了其他子复选框,父复选框仍未选中。
$("#firstParent").on('change', function() {
$('.child-1').prop('checked', this.checked);
});
$(".child-1").on('change', function() {
$('#firstParent').prop('checked', this.checked);
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="firstParent"><input type="checkbox" id="firstParent"/>Property</label>
<ul class="first-parent-child">
<li>
<lable>
<input type="checkbox" class="child-1" id="f-1" /> Edit Property
</lable>
</li>
<li>
<lable>
<input type="checkbox" class="child-1" id="f-2" /> Add Property
</lable>
</li>
<li>
<lable>
<input type="checkbox" class="child-1" id="f-3" /> Remove Property
</lable>
</li>
</ul>
发布于 2018-02-07 11:21:54
首先,注意没有lable元素;它是<label>。
要实现所需的目标,可以使用DOM遍历来查找相关的子复选框,以找到已更改的子复选框。这种模式的优点是它适用于任意数量的嵌套复选框级别。试试这个:
$(':checkbox').change(function() {
// child
$(this).closest('label').next('ul').find(':checkbox').prop('checked', this.checked);
// parent
$(this).closest('ul').prev('label').find(':checkbox').prop('checked', this.checked);
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<label>
<input type="checkbox" /> Property
</label>
<ul>
<li>
<label>
<input type="checkbox" />
Edit Property
</label>
<ul>
<li>
<label>
<input type="checkbox" />
Sub property #1
</label>
</li>
<li>
<label>
<input type="checkbox" />
Sub property #2
</label>
</li>
</ul>
</li>
<li>
<label>
<input type="checkbox" />
Add Property
</label>
</li>
<li>
<label>
<input type="checkbox" />
Remove Property
</label>
</li>
</ul>
https://stackoverflow.com/questions/48662394
复制相似问题