jQuery的attr()方法行为

时间:2016-06-10 13:05:40

标签: jquery

这不是' attr() vs prop() '问题。

考虑使用这么简单的网络表单:

<form action="/">
    <input type="radio" name="type" value="1" checked>
    <input type="radio" name="type" value="2" >
    <input type="radio" name="type" value="3" >
    <input type="radio" name="type" value="4" >
    <button type="submit"> Submit </button>
</form>

第一个单选按钮默认为checked属性,打开此网页表单会显示一个众所周知的图片:

enter image description here

在一个书面的jQuery脚本文件中,我试图检查一个单选按钮 - 但是可以使用prop()以正确且无头痛的方式完成,我选择attr()

使用浏览器控制台,我可以立即检查结果:

enter image description here

enter image description here

但是我知道在检查所需的输入之前我应该​​取消选中所有输入以获得正确的结果:

enter image description here

enter image description here

争论从这里开始,重复第一步:

enter image description here

enter image description here

我的问题是为什么会这样?单选按钮中没有复选标记,服务器端没有值。

1 个答案:

答案 0 :(得分:0)

问题是特定于jQuery版本。它根本不是一个bug,也没有附带jQuery v3 alpha版本。

但是后来,从jQuery v3 beta版本开始,removeAttr()发生了一些变化。

在jQuery中&lt; 3。* removeAttr()方法将动态/当前状态设置为false:

// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
    elem[ propName ] = false;

另一方attr()只设置默认状态(不是当前状态)。但是在jQuery &gt; = 3.0 中,我们不再看到这些行了。

在除v3。*(&gt;最终版和测试版)之外的所有版本中,我们不能指望从这两行检查单选按钮:

$('input[name="type"]').removeAttr('checked');
$('input[value="3"]').attr('checked', true);

但这三条线并排在一起:

$('input[name="type"]').removeAttr('checked');
$('input[value="3"]').attr('checked', true);
$('input[value="3"]').prop('checked', true);

或者更简单:

$('input[name="type"]').removeAttr('checked');
$('input[value="3"]').prop('checked', true);

(但请注意,某些javascript代码可能会检查属性而不是属性。因此,您必须额外执行.atrr()

同样在早期版本中,最好不要使用removeAttr(),而只使用attr(),如下所示:

$('input[name="type"]:checked').attr('checked', false);
$('input[type="3"]').attr('checked', true);

removeAttr()的行为更改也在Github上讨论。

感谢那些对此问题发表评论的人。

相关问题