使用JQuery检查单独div中的多个复选框

时间:2011-08-18 16:46:01

标签: javascript jquery html checkbox

我有几个复选框分布在两个div上。这两个div包含在一个名为actions的div中。 在一个单独的div中,我有一个'全选'复选框。当选中该复选框时,我试图选择所有其他复选框,当您取消选择“全选”时,它会取消选择其他复选框。

这是HTML:

<div class="actions" id="actions" title="Actions">
    <div>
        <div><input type="checkbox" name="action" class="act" value="0" /> <?php echo $lang["actions"][0]; ?></div><br />
        <div><input type="checkbox" name="action" class="act" value="1" /> <?php echo $lang["actions"][1]; ?></div><br />
        <div><input type="checkbox" name="action" class="act" value="2" /> <?php echo $lang["actions"][2]; ?></div><br />
        <div><input type="checkbox" name="action" class="act" value="3" /> <?php echo $lang["actions"][3]; ?></div><br />

    </div>
    <div>
        <div><input type="checkbox" name="action" class="act" value="26" /> <?php echo $lang["actions"][26]; ?></div><br />
        <div><input type="checkbox" name="action" class="act" value="27" /> <?php echo $lang["actions"][27]; ?></div><br />
        <div><input type="checkbox" name="action" class="act" value="28" /> <?php echo $lang["actions"][28]; ?></div><br />
        <div><input type="checkbox" name="action" class="act" value="29" /> <?php echo $lang["actions"][29]; ?></div><br />
        <div><input type="checkbox" name="action" class="act" value="30" /> <?php echo $lang["actions"][30]; ?></div><br />
        <div><input type="checkbox" name="action" class="act" value="31" /> <?php echo $lang["actions"][31]; ?></div>
    </div>
</div>
<div class="parameters1">
    <div class="selectAll" title="Select All"><input type="checkbox" id="selectAll" name="selectall" /> Select All</div>
</div>

这是我的JQuery:

$(".selectAll").click(function() {
        var checked_status = this.checked;
        $('#actions').find("input").each(function() {
            $(this).attr(":checked", checked_status);
        });
});

如果我在每个函数中放入一个alert(),它会正确地看到每一个复选框,但$(this).attr位似乎并没有真正改变复选框。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您没有正确设置属性:

    $(this).prop("checked", checked_status);

从jQuery的1.6版本开始,为了这个目的,“。prop()”优先于“.attr()”,但是对于像“checked”这样的布尔属性/属性,“。attr()”函数将还在工作。属性名称需要前面的“:”,实际上这将使操作失败,因为您要更新的属性实际上被称为“已检查”,没有“:”

你也不需要明确的“.each()”;它应该可以正常工作:

    $('#actions input').prop('checked', checked_status);
相关问题