3

我的表单上有两个单选按钮,直到我开始使用 jQuery 1.6,以下代码运行良好:

<input type="radio" id="radio1" name="test"/>
<input type="radio" id="radio2" name="test"/>
<input type="button" onclick="testcheck()" value="Test"/>
<script>
function testcheck()
{
    if (jQuery("#radio1").attr("checked"))
        alert("first button checked");
    else if (jQuery("#radio2").attr("checked"))
        alert("second button checked");
    else
        alert("none checked")      
}
</script>

一旦我开始使用 jQuery 1.6,它总是显示“未选中”,因为jQuery(radiobutton).attr("checked")它总是空的。

看看这个jsfiddle,并在 1.5.2 和 1.6 之间更改 jQuery 版本,看看我的意思。

4

6 回答 6

8

看看这个问题:.prop() vs .attr()

试试这个代替你的代码:

function testcheck()
{
    if (jQuery("#radio1").prop("checked"))
        alert("first button checked");
    else if (jQuery("#radio2").prop("checked"))
        alert("second button checked");
    else
        alert("none checked")      
}

同样在最新的jQuery 1.6.1中,他们修复了 1.6 的一些attr问题

于 2011-05-11T19:35:02.170 回答
3

这不是一个错误,而是一个变化:

http://christierney.com/2011/05/06/understanding-jquery-1-6s-dom-attribute-and-properties/

此外,正如@Neal 所提到的,他们在最新的1.6.1 候选版本中对此进行了一些研究。

从 RC 链接:

从 1.5.2 升级到 1.6.1 - 随着新的 .prop() 方法的引入和对 .attr() 方法的更改,jQuery 1.6 引发了关于属性和属性之间的差异以及它们如何相互关联的讨论其他。它还带有一些已在 1.6.1 中修复的向后兼容性问题。从 1.5.2 更新到 1.6.1 时,您不必更改任何代码。

那里有更多解释,但您可能可以跳到 1.6.1 并且没问题...

编辑 - 在 2011 年 5 月 16 日在下面添加

约翰·雷西格(John Resig)刚刚权衡了围绕这一点所做的改变以及为什么……读得好……

http://ejohn.org/blog/jquery-16-and-attr/

于 2011-05-11T19:35:45.383 回答
3

我也一直在看这个。其他答案对为什么会这样以及何时恢复(仅适用于吸气剂?)有一些见解;与此同时,我一直在使用

$('#thingy').is(':checked');

作为跨版本的解决方法。

希望这可以帮助!

于 2011-05-11T19:39:29.970 回答
0

我无法解释版本之间的变化,但有一个选择器专门寻找检查 - http://api.jquery.com/checked-selector/

于 2011-05-11T19:39:36.330 回答
0

你可以这样破解它:jQuery("input[name='test']:checked")

演示:

http://jsfiddle.net/8Eqpu/15/

于 2011-05-11T19:39:42.150 回答
0

.attr()并且.data()在 jQuery 1.6 中发生了巨大的变化。

在这篇文章中有更好的解释:

升级到 jQuery 1.6:您可能面临的问题

希望这可以帮助。干杯

于 2011-05-12T05:22:48.690 回答