jQuery("checked",true)工作,然后不起作用?



请查看

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. 再次单击设置。这将输入"新预设值",但不会选中第二个复选框。

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

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

您需要使用.prop()来设置选中的属性

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

演示

属性与属性

使用道具() attr ()

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

最新更新