【问题标题】:jQuery ("checked", true) works, then doesn't work?jQuery ("checked", true) 工作,然后不工作?
【发布时间】:2014-03-16 09:49:14
【问题描述】:

Please see this Fiddle

HTML:

<form>
  <button type="button" class="form-clear">Clear</button>
  <button type="button" class="form-set">Set</button>
  <input type="text" value="Preset value" />
  <input type="checkbox" checked/>
  <input type="checkbox" />
</form>

jQuery:

$(".form-clear").click(function(){
  $(':input').not(':button, :submit, :reset, :hidden').val('');
  $(':checkbox, :radio').attr('checked', false);
});
$(".form-set").click(function(){
  $(':input').not(':button, :submit, :reset, :hidden').val('New preset value');
  $(':checkbox, :radio').attr('checked', true);
});
  1. 先点击设置。这将输入“新预设值”并选中第二个复选框。
  2. 点击清除清除整个表单。
  3. 再次单击设置。这将输入“新预设值”但不会选中第二个复选框。

我猜这两个函数之间有冲突?

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    关于checked 属性最重要的概念是它不对应于checked 属性。 属性其实对应defaultChecked属性,应该只用来设置复选框的初始值。

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

    $(".form-clear").click(function(){
        $(':input').not(':button, :submit, :reset, :hidden').val('');
        $(':checkbox, :radio').prop('checked', false);
    });
    $(".form-set").click(function(){
        $(':input').not(':button, :submit, :reset, :hidden').val('New preset value');
        $(':checkbox, :radio').prop('checked', true);
    });
    

    【讨论】:

      【解决方案2】:

      需要使用.prop()来设置checked属性

      $(':checkbox, :radio').prop('checked', true);
      

      Demo

      Attributes vs. Properties

      【讨论】:

      • 值得一提的是,checked 是一个布尔属性。
      【解决方案3】:

      使用 prop() 代替 attr()

      $(':checkbox, :radio').prop('checked', true);

      【讨论】:

        猜你喜欢
        • 2017-09-20
        • 2013-02-22
        • 2015-06-02
        • 2011-11-13
        • 1970-01-01
        • 2015-08-14
        • 1970-01-01
        • 2015-03-10
        • 1970-01-01
        相关资源
        最近更新 更多