【问题标题】:Check the child checkboxes onclick of parent checkbox选中父复选框的子复选框
【发布时间】:2014-09-27 19:52:07
【问题描述】:

我有一个 html 代码,其中分别有两个父复选框及其子复选框。 Onclick of parent 复选框应选中属于该父级的子级。就我而言,如果我选中父复选框,则会选中所有子复选框。我知道这是类名的问题,我可以用两个不同的类名命名并解决问题。但我无法更改类名。应该是一样的。我该如何解决这个问题??

index.html

        Parent1<input name="parent" class="pc-box" type="checkbox">
        Child 1<input class="check" name="child" type="checkbox">
        Child 2<input class="check" name="child" type="checkbox">
        Child 3<input class="check" name="child" type="checkbox">
        <br>
        Parent2<input name="parent" class="pc-box" type="checkbox" >
        Child 1 <input class="check" name="child" type="checkbox">
        Child 2 <input class="check" name="child" type="checkbox">
        Child 3 <input class="check" name="child" type="checkbox">

index.js

$(document).ready(function() {

$(".pc-box").click(function() {
if (this.checked) {
       ('.check').prop('checked',$(this).prop('checked'));
    }

 });
   });

here is my fiddle

【问题讨论】:

    标签: javascript jquery html checkbox


    【解决方案1】:

    您可以使用nextUntil 让子复选框跟随父复选框。如果您删除 if 语句,您还可以将父级设置为切换。

    $('.pc-box').change(function() {
        $(this).nextUntil('.pc-box').prop('checked', $(this).prop('checked')); 
    });
    

    Example fiddle

    【讨论】:

    • 没问题,很乐意提供帮助。
    【解决方案2】:

    在条件中设置复选框值时,您错过了 jquery 选择器。您还需要修改选择器以仅针对作为父级的下一个 .pc-box 复选框之前的元素。使用:

    $(document).ready(function() {
    $(".pc-box").click(function() {
     if (this.checked) {
       $(this).nextUntil('.pc-box').prop('checked',$(this).prop('checked'));
     }
    });});
    

    Demo

    【讨论】:

    • 你的答案总是准确的,lil 的解释对其他人甚至对 OP 都有帮助,就像冰淇淋上的樱桃一样 :)
    猜你喜欢
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多