javascript jQuery 1.9.1 中的单选按钮是否存在错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15844852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:17:51  来源:igfitidea点击:

Is there a bug with radio buttons in jQuery 1.9.1?

javascriptjquerydebuggingjquery-selectors

提问by Simon

I've been trying to programatically select radio buttons with jQuery, something I thought would be as simple as changing the checked attribute.

我一直在尝试使用 jQuery 以编程方式选择单选按钮,我认为这就像更改选中的属性一样简单。

However, the following code doesn't seem to do what is expected in jQuery 1.9.1 in Chrome/Firefox.

但是,以下代码似乎没有在 Chrome/Firefox 中执行 jQuery 1.9.1 中的预期。

Expected behaviour:Click the div enclosing the radio button -> 'checked' attribute gets set -> renders checked in the DOM.

预期行为:单击包含单选按钮的 div -> 'checked' 属性被设置 -> 在 DOM 中检查渲染。

Actual behaviour:Click the div enclosing the radio button -> 'checked' attribute gets set -> renders checked in the DOM for the first and second button clicked, subsequent buttons don't render as checked.

实际行为:单击包含单选按钮的 div -> 'checked' 属性被设置 -> 在 DOM 中为单击的第一个和第二个按钮呈现选中状态,后续按钮不会呈现为选中状态。

jQuery:

jQuery:

$('div.form-type-radio').on('click', function () {    
    var Id = $(this).find('input[type=radio]').attr('id');   
    $('form input[type=radio]:not(#'+Id+')').removeAttr('checked');   
    $('#' + Id).attr('checked', 'checked');    
    console.log($('#' + Id));    
});

Here's a jsFiddle - http://jsfiddle.net/GL9gC/

这是一个 jsFiddle - http://jsfiddle.net/GL9gC/

I've tried the same code with previous versions of jQuery and it all works as expected.

我已经用以前版本的 jQuery 尝试了相同的代码,并且一切都按预期工作。

回答by dsgriffin

In this case, you should use prop()instead of attr()/removeAttr().

在这种情况下,您应该使用prop()而不是attr()/ removeAttr()

Here's a working jsFiddle.

这是一个有效的jsFiddle

jQuery:

jQuery:

$('div.form-type-radio').on('click', function () {
    var Id = $(this).find('input[type=radio]').prop('id');
    $('form input[type=radio]:not(#'+Id+')').prop('checked');
    $('#' + Id).prop('checked', 'checked');
    console.log($('#' + Id));
});

回答by Roko C. Buljan

LIVE DEMO

LIVE DEMO

$('div.form-type-radio').on('click', function () {    
    $(this).find(':radio').prop({checked: true});
});

http://api.jquery.com/prop/

http://api.jquery.com/prop/