Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用于嵌套'的Javascript;选择全部';复选框_Javascript_Jquery - Fatal编程技术网

用于嵌套'的Javascript;选择全部';复选框

用于嵌套'的Javascript;选择全部';复选框,javascript,jquery,Javascript,Jquery,我试图显示一个复选框列表,每个项目都有一个“全选”选项,每个组都有一个“全选”选项 我有以下标记: <fieldset> <label> <input type="checkbox" class="checkall"><strong> All</strong> </label> <fieldset> <l

我试图显示一个复选框列表,每个项目都有一个“全选”选项,每个组都有一个“全选”选项

我有以下标记:

    <fieldset>
        <label>
            <input type="checkbox" class="checkall"><strong> All</strong>
        </label>
        <fieldset>
            <label>
                <input type="checkbox" name="checkedLocations" class="chkChild checkall" value="China" />
                <strong>&nbsp;&nbsp;China</strong>
            </label>
            <label>
                <input type="checkbox" name="checkedLocations" class="chkChild" value="Hong Kong" checked="checked" />
                &nbsp;&nbsp;&nbsp;Hong Kong
            </label>
        </fieldset>
        <fieldset>
            <label>
                <input type="checkbox" name="checkedLocations" class="chkChild checkall" value="Australia" />
                <strong>&nbsp;&nbsp;Australia</strong>
            </label>
            <label>
                <input type="checkbox" name="checkedLocations" class="chkChild" value="NSW" />
                &nbsp;&nbsp;&nbsp;NSW
            </label>

            <label>
                <input type="checkbox" name="checkedLocations" class="chkChild" value="VIC" />
                &nbsp;&nbsp;&nbsp;VIC
            </label>
        </fieldset>
    </fieldset>

“全选”也可以,但是当我点击中国或澳大利亚时,复选框不起作用,子项也不会被选中/取消选中。

因为您在该元素上有两个类

$(function () {
    $('.checkall').on('click', function () {
        $(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
    });
    $('.chkChild').on('click', function () {
        if (!$(this).is('.checkall')) {
            $(this).closest('fieldset').find('.checkall').prop('checked', false);
        }
    });
});

演示:

您知道“澳大利亚”和“中国”也有“checkall”类吗?是的,当时它很有意义。:-)跟进问题
$(function () {
    $('.checkall').on('click', function () {
        $(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
    });
    $('.chkChild').on('click', function () {
        if (!$(this).is('.checkall')) {
            $(this).closest('fieldset').find('.checkall').prop('checked', false);
        }
    });
});