javascript 选择元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6069112/
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
javascript select element
提问by qwera
I have a select element like this
我有一个像这样的选择元素
<select name ="cars">
<option value="frd"> Ford </option>
<option value="hdn"> Holden </option>
<option value="nsn"> Nissan </option>
</select>
I want to set selected to "Holden" with javascript without selected by value. how can I achieve this?
我想使用 javascript 将 selected 设置为“Holden”,而无需按值选择。我怎样才能做到这一点?
Thanks in advance
提前致谢
回答by Gabriele Petrioli
updateafter comment
评论后更新
Use the following to find the option by text and select it
使用以下通过文本查找选项并选择它
var optionlist = document.getElementById('cars').options;
for (var option = 0; option < optionlist.length; option++ )
{
if (optionlist[option].text == 'Holden')
{
optionlist[option].selected = true;
break;
}
}
demo athttp://jsfiddle.net/gaby/vQhfq/
演示在http://jsfiddle.net/gaby/vQhfq/
original
原来的
When there is no value attribute specified for option elements, they assume the value to be the text.
当没有为选项元素指定 value 属性时,它们假定值是文本。
I would suggest you use an id, so you can easily find the element.
我建议您使用 id,这样您就可以轻松找到该元素。
Html
html
<select name ="cars" id="cars">
<option> Ford </option>
<option> Holden </option>
<option> Nissan </option>
</select>
javascript
javascript
document.getElementById('cars').value = 'Holden';
(make sure you run this code, after the select element is created)
(确保在创建选择元素后运行此代码)
回答by RobG
To select the option by its text, get a reference to the select, iterate over the options looking for the one with text "Holden", then either set the select's selectedIndexproperty to the index of the option, or set the option's selectedproperty to true. e.g.
要通过文本选择选项,请获取对选择的引用,遍历选项以查找带有文本“Holden”的选项,然后将选择的selectedIndex属性设置为选项的索引,或将选项的selected属性设置为真的。例如
function setSelectedByText(id, text) {
var select = document.getElementById(id);
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i++) {
opt = options[i];
if (opt.text == text) {
opt.selected = true;
// or
select.selectedIndex = i;
}
}
}
For the record, the value of the select element is the value of the selected option, or, if the selected option has no value, it's text. However, IE gets it wrong and returns "" if the option has no value.
对于记录,select 元素的值是所选选项的值,或者,如果所选选项没有值,则为文本。但是,如果选项没有值,IE 会出错并返回“”。
Also, if you don't want to use getElementById, you can use:
此外,如果您不想使用 getElementById,您可以使用:
var select = document.formName.selectName;
Noting that the select element must have a name to be successful (i.e. for its value to be returned when the form it's in is submitted).
请注意,select 元素必须有一个名称才能成功(即在提交它所在的表单时返回它的值)。