下面的代码有两组复选框,每组都由div类拆分EachCategorySet
。
当我单击一个parent
复选框时,它应该选中它的所有child1
child2
复选框,但是它应该保留在class定义的组中EachCategorySet
。
但是使用当前代码,如果我单击A1
复选框,它将检查所有相同的类复选框,而不会遵守其组div class EachCategorySet
。如何将其限制为仅在div类中检查EachCategorySet
而不检查下一组div?
这是JsFiddle
HTML:
<div class="EachCategorySet">
<div class="accordion-heading">
<input type="checkbox" class="parent" name="parent"> A1
</div>
<input type="checkbox" class="child1" name="child1"> A2
<input type="checkbox" class="child2" name="child2"> A3
</div>
<br/>
<div class="EachCategorySet">
<div class="accordion-heading">
<input type="checkbox" class="parent" name="parent"> B1
</div>
<input type="checkbox" class="child1" name="child1"> B2
<input type="checkbox" class="child2" name="child2"> B3
</div>
jQuery的:
//parent class checkbox action
$(".parent").change(function () {
if (this.checked) {
$('.child1').prop("checked", this.checked);
$('.child2').prop("checked", this.checked);
}
});
//child1 checkbox action
$(".child1").change(function () {
if (this.checked) {
$('.child2').prop("checked", this.checked);
}
});
这样的事情。
请注意,通过使用该信息this.checked
可以知道是否选中了父复选框,因此可以使用该值将子复选框设置为相同的值-因此,您只需要一个功能。
//parent class checkbox action
$(".parent").change(function() {
$(this).parent().find('.child1').prop("checked", this.checked);
$(this).parent().find('.child2').prop("checked", this.checked);
});
$(".child1").change(function() {
$(this).parent().find('.child2').prop("checked", this.checked);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="EachCategorySet">
<input type="checkbox" class="parent" name="parent">
A1
<input type="checkbox" class="child1" name="child1">
A2
<input type="checkbox" class="child2" name="child2">
A3
</div>
<br/>
<div class="EachCategorySet">
<input type="checkbox" class="parent" name="parent">
B1
<input type="checkbox" class="child1" name="child1">
B2
<input type="checkbox" class="child2" name="child2">
B3
</div>
参考:
在DOM树中上/下移动或从一个元素移到另一个元素称为DOM遍历。这是有关该主题的更多信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句