gpt4 book ai didi

jQuery - 我看不到任何错误

转载 作者:行者123 更新时间:2023-12-01 04:18:44 25 4
gpt4 key购买 nike

我必须在某些<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数组的key表示<select>的个数标签。这就是我想做的。

谁能告诉我错误是什么?

最佳答案

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

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

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

此外,在选项上设置选定的属性比您一开始想象的要复杂一些,因为如果选择元素的类型为“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);
});

关于jQuery - 我看不到任何错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12565288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com