jQuery 定位正确的单选按钮没有响应
我有一个 javascript 数组,其中包含我想要检查的无线电的名称和值。
jQuery(window).load(function(){
var selected_options = new Array();
selected_options['swing_type'] = 'Slide';
var x;
for (x in selected_options){
jQuery("#menu input[name="+ x +"][value="+ selected_options[x] +"]").attr('checked', 'checked');
}
});
html 中有这样的内容:
<td>
<input type="radio" id="swing" name="swing_type" value="Swing" /><label for="swing"> Swing</label><br />
<input type="radio" id="slide" name="swing_type" value="Slide" /><label for="slide"> Slide</label>
</td>
当我运行此脚本时,浏览器变得无响应。我尝试了一些变体,以下两个有效:
jQuery("#menu input[value="+ selected_options[x] +"]").attr('checked', 'checked');
jQuery("#menu input[name=swing_type][value=Swing]").attr('checked', 'checked');
以下无效:
jQuery("#menu input[name=swing_type][value="+ selected_options[x] +"]").attr('checked', 'checked');
我希望有人能启发我找出问题所在。我想定位正确的无线电输入。如果我只针对这些值,我可能会看到可能存在两个带有是/否值的单独集合的情况。谢谢。
I have a javascript array containing the name and values of radios I want checked.
jQuery(window).load(function(){
var selected_options = new Array();
selected_options['swing_type'] = 'Slide';
var x;
for (x in selected_options){
jQuery("#menu input[name="+ x +"][value="+ selected_options[x] +"]").attr('checked', 'checked');
}
});
And the html has something like:
<td>
<input type="radio" id="swing" name="swing_type" value="Swing" /><label for="swing"> Swing</label><br />
<input type="radio" id="slide" name="swing_type" value="Slide" /><label for="slide"> Slide</label>
</td>
When I run this script, the browser becomes unresponsive. I've tried a few variations, the following two worked:
jQuery("#menu input[value="+ selected_options[x] +"]").attr('checked', 'checked');
jQuery("#menu input[name=swing_type][value=Swing]").attr('checked', 'checked');
The following did not work:
jQuery("#menu input[name=swing_type][value="+ selected_options[x] +"]").attr('checked', 'checked');
I'm hoping someone can enlighten me to what is wrong. I want to target the correct radio inputs. If I only target the values, I could see a case where there could be two separate sets with Yes/No values. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在对数组执行 for/in 操作。这有时会导致问题。
由于您指定了命名键,因此您应该使用一个对象:
或
测试示例: http ://jsfiddle.net/Ds3s8/
You're doing a for/in over an Array. This can sometimes cause problems.
Since you are specifying named keys, you should use an object instead:
or
Test the example: http://jsfiddle.net/Ds3s8/