JQuery在选择列表上设置选定的属性 [英] JQuery setting the selected attribute on a select list
问题描述
我有以下html
< select id =dropdown>
< option> A< / option>
< option> B< / option>
< option> C< / option>
< / select>
我有字符串B,所以我想设置所选的attrribute,所以它会:
< select id =dropdown>
< option> A< / option>
< option selected =selected> B< / option>
< option> C< / option>
< / select>
我如何在JQuery中做到这一点?
< option> B< / option>
至
< option value =B> B< / option>
当您想要做类似的事情时,这会很有帮助:
< option value =IL>伊利诺伊< / option>
因此,下面的jQuery将进行更改:
$(select option [value ='B'])。attr(selected,selected);
如果您决定不包含使用 value
属性,您将被要求遍历每个选项,并手动检查其值:
<$ c $ ($(this).text()==B)
$(this).attr(selected)。 ,selected);
});
I have the following html
<select id="dropdown">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
I have the string "B" so I want to set the selected attrribute on it so it will be:
<select id="dropdown">
<option>A</option>
<option selected="selected">B</option>
<option>C</option>
</select>
How would I do this in JQuery?
If you don't mind modifying your HTML a little to include the value
attribute of the options, you can significantly reduce the code necessary to do this:
<option>B</option>
to
<option value="B">B</option>
This will be helpful when you want to do something like:
<option value="IL">Illinois</option>
With that, the follow jQuery will make the change:
$("select option[value='B']").attr("selected","selected");
If you decide not to include the use of the value
attribute, you will be required to cycle through each option, and manually check its value:
$("select option").each(function(){
if ($(this).text() == "B")
$(this).attr("selected","selected");
});
这篇关于JQuery在选择列表上设置选定的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!