我具有以下功能,可以通过选择一个来选中/取消选中页面上的所有复选框

$("#checkall").click(function() {
    var checked_status = this.checked;
    $("input:checkbox").each(function() {
        this.checked = checked_status;
    });
});


我需要通过以下方式进行修改:如果所有内容都通过单击checkall选中,然后未选中,则#checkall也将被取消选中。还是我需要为此创建一个单独的功能?

同样,当选中“无”复选框时,我需要将一个类添加到另一个元素。

$("#myElement").addClass("disabled");


将所有这些放在一起会使我的事情变得复杂。

最佳答案

我会使用更改事件。

这是您所追求的吗?:

<div class="checkall">
    <input type="checkbox" id="checkall">
</div>
<div id="list">
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
</div>


和jQuery的:

var checkboxes = $(":checkbox", "#list").change(function() {
        var allIsChecked = checkboxes.length === checkboxes.filter(":checked").length;

        checkAll[0].checked = allIsChecked;
});

var checkAll = $("#checkall").change(function() {
        checkboxes.prop("checked",this.checked);
});


演示(如果您使用的是jQuery 1.6+):
http://jsbin.com/ezofal/edit

在此链接中添加了#MyElement类切换:http://jsbin.com/ezofal/2/edit

关于jquery - 使用/jQuery选中/取消选中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7365644/

10-12 12:39
查看更多