【问题标题】:jQuery to check and uncheck checkboxes only fires oncejQuery 检查和取消选中复选框只触发一次
【发布时间】:2013-01-18 18:15:59
【问题描述】:

我对我的 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/

【问题讨论】:

  • 使用.prop() 而不是.attr()

标签: javascript jquery checkbox


【解决方案1】:

将您的 .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 example

您也可以将其简化为:

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

jsFiddle example

作为.attr() 状态的文档:

从 jQuery 1.6 开始,.attr() 方法返回未定义的属性 尚未设置。 检索和更改 DOM 属性,例如 表单元素的选中、选择或禁用状态,使用 .prop() 方法。

【讨论】:

  • 谢谢!我不知道 prop() 我会阅读它。时间到了,我会接受你的回答。
  • 刚刚也帮我解决了这个问题 - 你能解释一下区别以及为什么一个有效而另一个无效吗?
  • @asfallows- 我可以尝试,但 jQuery 文档已经有详尽的解释:api.jquery.com/attr
【解决方案2】:

我知道这在这里被骗了很多,但我确实错过了一些东西,我有:

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

如上所述,ALL 的 attr 情况需要替换为 prop()

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

希望对某人有所帮助...

【讨论】:

  • 太棒了!这个对我有用。在 chrome 中使用 .prop() 而不是 attr()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-05
  • 1970-01-01
  • 2013-06-29
相关资源
最近更新 更多