我想做类似的事情,但我无法以这种方式更改 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;
}
Run Code Online (Sandbox Code Playgroud)
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 ];
}
Run Code Online (Sandbox Code Playgroud)
如果您需要按值选择/分配选择,您可以迭代这些值,或者使用 qSA 或 jQuery 或 dojo 等库来获取它。
<select id="state-select">
<option value="1">NC</option>
<option value="2">SC</option>
</select>
Run Code Online (Sandbox Code Playgroud)
使用 jQuery
// select SC
$( '#state-select' ).val( 2 );
Run Code Online (Sandbox Code Playgroud)
迭代
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;
}
}
Run Code Online (Sandbox Code Playgroud)
为此,您无需对 做任何事情options,您可以通过.selectedIndex直接设置select 元素的属性来更改所选元素:
...
case 'VA':
selected.selectedIndex = 0;
break;
// etc.
Run Code Online (Sandbox Code Playgroud)
(假设这是一个单选选择元素。)
我相信如果您设置selectedIndex为 -1,它将不会选择任何选项。
| 归档时间: |
|
| 查看次数: |
25875 次 |
| 最近记录: |