jQuery(“checked”,true)起作用,然后不起作用? [英] jQuery ("checked", true) works, then doesn't work?

查看:284
本文介绍了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. 点击清除即可清除整个表单。 >再次点击设置。这将输入新预设值但不会选中第二个复选框。
  1. Click Set first. This will input "New preset value" and check the second checkbox.
  2. Click Clear to clear the whole form.
  3. Click Set again. This will input "New preset value" but will not check the second checkbox.

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

I'm guessing there's a conflict between the two functions?

推荐答案

关于checked属性最重要的概念是它不符合检查的属性。 属性实际上与 defaultChecked属性相对应,并且只应用于设置复选框的初始值。

The most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox.

使用 .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);
});

这篇关于jQuery(“checked”,true)起作用,然后不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆