jQuery 定位正确的单选按钮没有响应

发布于 2024-09-07 11:15:02 字数 1123 浏览 2 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

度的依靠╰つ 2024-09-14 11:15:02

您正在对数组执行 for/in 操作。这有时会导致问题。

由于您指定了命名键,因此您应该使用一个对象:

var selected_options = {};

var selected_options = new Object();

测试示例: 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:

var selected_options = {};

or

var selected_options = new Object();

Test the example: http://jsfiddle.net/Ds3s8/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文