【问题标题】:Why select/deselect checkbox works only once with jQuery?为什么选择/取消选择复选框只能与 jQuery 一起使用?
【发布时间】:2014-09-14 15:23:28
【问题描述】:

我有一个简单的选择/取消选择选项来选中和取消选中页面中的复选框。它运作良好,但只有一次。不知道是什么问题!
请看一下我的代码。你可以看到它的demo here

HTML 代码:

<input type="checkbox" id="main" />Select All<br />
<input type="checkbox" class="options" />Item 1<br />
<input type="checkbox" class="options" />Item 2<br />
<input type="checkbox" class="options" />Item 3<br />
<input type="checkbox" class="options" />Item 4<br />

jQuery 代码:

$('#main').click(function(e) {
    $('.options').attr('checked', this.checked);
});

【问题讨论】:

    标签: jquery html checkbox html-select deselect


    【解决方案1】:

    您需要使用.prop() 而不是.attr()

    使用

    $('.options').prop('checked', this.checked);
    

    一本好书.prop() vs .attr()

    【讨论】:

    • 谢谢@Satpal。它解决了这个问题。你能告诉我这里的 prop 和 attr 有什么区别吗?
    • @MohammadSaberi,您应该阅读答案中提到的stackoverflow.com/questions/5874652/prop-vs-attr。由于checked 是一个属性,你应该使用上述方法
    猜你喜欢
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    相关资源
    最近更新 更多