使用jQuery在选择列表上设置selected属性 [英] Setting the selected attribute on a select list using jQuery
问题描述
我有以下HTML:
<select id="dropdown">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
我有字符串"B",所以我想在其上设置selected
属性,这样它将是:
I have the string "B" so I want to set the selected
attribute on it so it will be:
<select id="dropdown">
<option>A</option>
<option selected="selected">B</option>
<option>C</option>
</select>
我将如何在jQuery中做到这一点?
How would I do this in jQuery?
推荐答案
如果您不介意稍微修改HTML以包含选项的value
属性,则可以大大减少执行此操作所需的代码:
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>
到
<option value="B">B</option>
当您要执行以下操作时这将很有帮助:
This will be helpful when you want to do something like:
<option value="IL">Illinois</option>
有了这个,下面的jQuery将会做出改变:
With that, the follow jQuery will make the change:
$("select option[value='B']").attr("selected","selected");
如果您决定 not 不包括对value
属性的使用,则将需要循环浏览每个选项,并手动检查其值:
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在选择列表上设置selected属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!