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

标签 javascript jquery debugging jquery-selectors

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

但是,以下代码似乎无法在 Chrome/Firefox 中执行 jQuery 1.9.1 中预期的操作。

预期行为:单击包含单选按钮的 div -> 设置“选中”属性 -> 在 DOM 中呈现选中状态。

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

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

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

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

最佳答案

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

这是一个有效的 jsFiddle .

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

关于javascript - jQuery 1.9.1 中的单选按钮是否存在错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15844852/

相关文章:

jquery-ui - 表单字段的 jQuery 对话框发布

JavaScript 或 jquery : Can you load a page and then call a function?

visual-studio - Visual Studio 调试器输出 - 输出相同但格式不同(如一个项目中的十进制输出,另一个项目中的十六进制输出)

php - 如何让PHP显示错误? (我添加了 ini_set 和 error_reporting,但只给出 500 个错误)

c++ - 在 Visual C++ 2003 中删除调试符号

javascript - jquery hide 隐藏并立即再次显示

javascript - 如何使用 JavaScript 或 jQuery 读取 json 数据

javascript - 关于 keydown 事件的声明是什么意思?

javascript - CasperJS 中的 XPath 有什么问题?

javascript - JSON.parse 后嵌套 json 数据成为 [Object]