打开/关闭复选框 [英] Toggle Checkboxes on/off

查看:21
本文介绍了打开/关闭复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几点:

$(document).ready(function()
{
    $("#select-all-teammembers").click(function() {
        $("input[name=recipients\[\]]").attr('checked', true);
    });                 
});

我想要 id="select-all-teammembers" 单击以在选中和未选中之间切换.想法?那不是几十行代码吗?

I'd like the id="select-all-teammembers" when clicked to toggle between checked and unchecked. Ideas? that aren't dozens of lines of code?

推荐答案

你可以写:

$(document).ready(function() {
    $("#select-all-teammembers").click(function() {
        var checkBoxes = $("input[name=recipients\[\]]");
        checkBoxes.prop("checked", !checkBoxes.prop("checked"));
    });                 
});

在 jQuery 1.6 之前,我们只有 attr() 而不是 prop(),我们曾经这样写:

Before jQuery 1.6, when we only had attr() and not prop(), we used to write:

checkBoxes.attr("checked", !checkBoxes.attr("checked"));

但是 prop() 在应用于boolean"HTML 属性时比 attr() 具有更好的语义,因此在这种情况下通常首选.

But prop() has better semantics than attr() when applied to "boolean" HTML attributes, so it is usually preferred in this situation.

这篇关于打开/关闭复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆