Javascript 如何使用 getElementById 更改选择元素的 selectedIndex
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8438697/
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
How to change the selectedIndex of a select element using getElementById
提问by Darren
I want to do something similar to this but I am unable to change the selectedIndex value this way:
我想做类似的事情,但我无法以这种方式更改 selectedIndex 值:
var selected = document.getElementById("state-select");
switch (state) {
case 'VA':
selected.options[selected.selectedIndex] = 0;
break;
case 'NC':
selected.options[selected.selectedIndex] = 1;
break;
case 'SC':
selected.options[selected.selectedIndex] = 2;
break;
}
回答by Dan Heberden
switch
statements are cool, but using a hash to do the work can be a lot more flexible. As seen below, you can just check if the state is in the hash, and if so, use it.
switch
语句很酷,但是使用散列来完成这项工作可以更加灵活。如下所示,您可以只检查状态是否在哈希中,如果是,则使用它。
var selected = document.getElementById("state-select"),
states = { 'VA' : 0,
'NC' : 1,
'SC' : 2
};
// if `state` ( not sure what it is ) is in the hash
if ( states[ state ] !== undefined ) {
//select option based on the hash
selected.selectedIndex = states[ state ];
}
if you need to select/assign-the-select by value, you can iterate over the values, or use qSA or a library like jQuery or dojo to get it.
如果您需要按值选择/分配选择,您可以迭代这些值,或者使用 qSA 或像 jQuery 或 dojo 这样的库来获取它。
<select id="state-select">
<option value="1">NC</option>
<option value="2">SC</option>
</select>
Using jQuery
使用 jQuery
// select SC
$( '#state-select' ).val( 2 );
Iterating
迭代
var sel = document.getElementById( 'state-select' ),
opts = sel.options;
// loop through the options, check the values
for ( var i = 0; i < opts.length; i++ ) {
// assuming 2 would be states[ state ] or whatevs
if ( opts[i] == 2 ) {
// set to this index
sel.selectedIndex = i;
// stop iterating
break;
}
}
回答by nnnnnn
For this purpose you don't need to be doing anything with options
, you can change the selected element by setting the .selectedIndex
property of your select element directly:
为此,您无需对 做任何事情options
,您可以通过.selectedIndex
直接设置select 元素的属性来更改所选元素:
...
case 'VA':
selected.selectedIndex = 0;
break;
// etc.
(Assuming this is a single-select select element.)
(假设这是一个单选选择元素。)
I believe if you set selectedIndex
to -1 it will leave no options selected.
我相信如果您设置selectedIndex
为 -1,它将不会选择任何选项。
回答by Jerry
Or selected.value = [option value]
或 selected.value = [选项值]
回答by Senad Me?kin
Try:
尝试:
selected.selectedIndex = [Your index]