Jquery - 通过 id 设置选择列表选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4159349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery - Setting a select list option by id
提问by SethPlante
I feel like this should not be this complicated, but I'm sure I'm missing something trivial. Thanks for anyone that can help!
我觉得这不应该这么复杂,但我确定我错过了一些微不足道的东西。感谢任何可以提供帮助的人!
XSL:
XSL:
<select id="mySelectList">
<option id="1" description="Blue" />
<option id="2" description="Black" />
<option id="3" description="Green" />
</select>
JS:
JS:
$("#mySelectList option[id='1']").attr("selected", "selected");
EDIT: Fixed my select per Nick's response.
编辑:根据尼克的回应修正了我的选择。
回答by Nick Craver
A <select>
should look like:
A<select>
应该如下所示:
<select id="mySelectList">
Or if you literally want the element and that's XML, remove the #
for an element selector, like this:
或者,如果您确实想要该元素并且是 XML,请删除#
for an element selector,如下所示:
$("mySelectList option[id='1']").attr("selected", "selected");
回答by Gnp
Your code should select what you want.
您的代码应该选择您想要的。
Are you sure that you want your <option>
to be without a text value ?
您确定要<option>
没有文本值吗?
Maybe you want
也许你想要
<select id="mySelectList">
<option id="1" description="Blue">Blue</option>
<option id="2" description="Black">Black</option>
<option id="3" description="Green">Green</option>
</select>
Also keep in mind that you select the first item, which is selected by default.
还要记住,您选择了默认情况下选中的第一项。
example at http://www.jsfiddle.net/Zfx3e/
回答by lonesomeday
In HTML4, ID attributes must begin with a letter, not a number (see the specifications). E.g.
在 HTML4 中,ID 属性必须以字母开头,而不是数字(请参阅规范)。例如
<select id="mySelectList">
<option id="opt1" description="Blue" />
<option id="opt2" description="Black" />
<option id="opt3" description="Green" />
</select>
So you could do
所以你可以这样做
$('#mySelectList option[id="opt1"]);