Javascript 如何使用getElementById更改select元素的selectedIndex
我想执行类似操作,但无法通过以下方式更改selectedIndex值:Javascript 如何使用getElementById更改select元素的selectedIndex,javascript,Javascript,我想执行类似操作,但无法通过以下方式更改selectedIndex值: var selected = document.getElementById("state-select"); switch (state) { case 'VA': selected.options[selected.selectedIndex] = 0; break;
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;
}
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 ];
}
如果需要选择/分配select by值,可以迭代这些值,或者使用qSA或类似于jQuery或dojo的库来获取它
<select id="state-select">
<option value="1">NC</option>
<option value="2">SC</option>
</select>
迭代
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;
}
}
var sel=document.getElementById('state select'),
opts=选择选项;
//循环浏览选项,检查值
对于(变量i=0;i
为此,您无需使用选项执行任何操作
,您可以通过直接设置select元素的属性来更改选定元素:
...
case 'VA':
selected.selectedIndex = 0;
break;
// etc.
(假设这是单个选择元素。)
我相信如果您将selectedIndex
设置为-1,则不会保留任何选项。尝试:
selected.selectedIndex = [Your index]
或者selected.value=[option value]您是否尝试过selected.selectedIndex=0Wow,成功了!不幸的是,我不能标记为答案,因为您是作为评论提交的。你能重新提交答案吗?
selected.selectedIndex = [Your index]