jQuery检查和取消选中复选框只触发一次

10
我有一个非常简单的需求,就是使用jQuery检查一组复选框是否已选中,如果选择了一个单选按钮,则清除所有复选框。这个jQuery代码实现了这个功能,但它只能工作一次 - 如果我点击选择全部(所有复选框被选中),然后再点击取消选择(所有复选框取消选中),再次点击选择全部时,没有效果。同样,如果我手动取消选中某些框,然后再次点击选择全部,也没有效果。jQuery 代码:
$('#all').on('change', function() {
    if (!$(this).is(':checked')) {
        $('.country').attr('checked', false);   
    } else {
        $('.country').attr('checked', true);
    }
});


$('#none').on('change', function() {
    if (!$(this).is(':checked')) {
        $('.country').attr('checked', true);    
    } else {
        $('.country').attr('checked', false);
    }
});

HTML

 <div class="subselect">
    <input type="radio" class="TLO" name="radio1" id="all" />Check All
<br />
        <input type="radio" class="TLO" name="radio1" id="none" />Clear All
        <br />
    </div>

    <br />
    <br />
    <div class="cselect" id="countries">
        <input type="checkbox" class="country"  />1
        <br />
        <input type="checkbox" class="country"  />2
        <br />
        <input type="checkbox" class="country"  />3
    </div>

jsFiddle http://jsfiddle.net/vsGtF/1/


2
使用 .prop() 替代 .attr() - David
2个回答

35

将您的.attr()更改为.prop()

$('#all').on('change', function() {
    if (!$(this).is(':checked')) {
        $('.country').prop('checked', false);   
    } else {
        $('.country').prop('checked', true);
    }
});    
$('#none').on('change', function() {
    if (!$(this).is(':checked')) {
        $('.country').prop('checked', true);    
    } else {
        $('.country').prop('checked', false);
    }
});

jsFiddle示例

你还可以将其简化为:

$('#all').on('change', function () {
    $('.country').prop('checked', $(this).is(':checked'));
});
$('#none').on('change', function () {
    $('.country').prop('checked', !$(this).is(':checked'));
});

jsFiddle 示例

正如.attr()文档所述:

自 jQuery 1.6起,对于未设置的属性,.attr()方法返回undefined。要检索和更改表单元素的选中、禁用或选定状态等DOM属性,请使用.prop()方法。


谢谢!我不知道prop(),我会了解一下。当计时结束时,我会接受你的答案。 - Gideon
刚刚帮我解决了这个问题 - 你能否解释一下它们之间的区别以及为什么一个可行而另一个不行? - asfallows
1
我可以尝试,但是jQuery文档已经有了详细的解释:http://api.jquery.com/attr/ - j08691

4

我知道这个问题在这里已经被重复提出了很多次,但是我错过了一些东西,我有:

id = $(this).attr('id');
if($('#checkbox_' + id).prop('checked')){
    $('#checkbox_' + id).attr('checked', false);
} else {
    $('#checkbox_' + id).attr('checked', true);
}

正如上面提到的,所有 attr 的情况都需要切换为 prop()。

if($('#checkbox_' + id).prop('checked')){
    $('#checkbox_' + id).prop('checked', false);
} else {
    $('#checkbox_' + id).prop('checked', true);
}

希望这能对某些人有所帮助...


太好了!它对我有效。在Chrome中使用.prop()有效而不是.attr()。 - Rahul Mankar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接