jQuery(“checked”,true)有效,然后不起作用?

时间:2014-03-16 09:49:14

标签: javascript jquery html

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. 点击清除以清除整个表单。
  4.     
  5. 再次点击设置。这将输入“新预设值”但不会检查第二个复选框。
  6. 我猜这两个函数之间存在冲突吗?

3 个答案:

答案 0 :(得分:18)

要记住关于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);
});

答案 1 :(得分:6)

您需要使用.prop()来设置已检查的属性

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

Demo

Attributes vs. Properties

答案 2 :(得分:0)

使用 prop() 代替 attr()

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