jQuery - 我看不到任何错误

时间:2012-09-24 12:45:08

标签: jquery

我必须在某些<select>代码中选择正确的选项。我有一个数组,其中键是标签的数量,值是必须选择的选项的值属性。

这是我的代码:

//array ids contains values of option to select.
//.ingredients is class of <select> tags

var i=0;

$('.ingredients').each(function() {

$(this).find('option[value="' + ids[i] + '"]').attr("selected","selected");
i++                  
});

对于<select class='ingredients>的每个选项,请选择右侧选项字段。 ids数组的键表示<select>标记的数量。这就是我想要做的。

有人能告诉我错误是什么吗?

2 个答案:

答案 0 :(得分:2)

你忘记了一个“;”在i++ ...

之后

您可以将indexeach()一起使用,而不是使用“i”变量:

$('.ingredients').each(function(index) {
  $(this).find('option[value="' + ids[index] + '"]').attr("selected","selected");
});

另外,在一个选项上设置选定的attr比你最初想的那样有点棘手,因为如果select元素是'select-one'类型,它会影响其他元素。这是jQuery Form插件中提供的一个小插件,用于处理选择/取消选择选项以及复选框和无线电。像这样使用它:

将它放在代码中的某处:

$.fn.selected = function(select) {
    if (select == undefined) select = true;
    return this.each(function() {
        var t = this.type;
        if (t == 'checkbox' || t == 'radio')
            this.checked = select;
        else if (this.tagName.toLowerCase() == 'option') {
            var $sel = $(this).parent('select');
            if (select && $sel[0] && $sel[0].type == 'select-one') {
                // deselect all other options
                $sel.find('option').selected(false);
            }
            this.selected = select;
        }
    });
};

然后尝试替换您先给出的代码:

$('.ingredients').each(function(index) {
  $(this).find('option[value="' + ids[index] + '"]').selected(true);
});

答案 1 :(得分:0)

而不是.attr("selected", "selected"),请尝试.prop("selected", true)

[更新]

实际上,我没有看到代码有任何问题。这是工作。我认为问题出在你的HTML上。您是否在DOM Ready事件之前执行代码?

请参阅http://jsfiddle.net/VPcMx/

尝试

 $(function(){
    $('.ingredients').each(function(i) {

        $(this).find('option[value="' + ids[i] + '"]').prop("selected", true);
        i++                  
    });
});
相关问题