如何使用getElementById更改选定元素的selectedIndex

How to change the selectedIndex of a select element using getElementById

本文关键字:元素 selectedIndex 何使用 getElementById      更新时间:2023-09-26

我想做类似的事情,但我不能这样改变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;                       
}

对于这个目的,你不需要对options做任何事情,你可以通过直接设置你的选择元素的.selectedIndex属性来改变所选择的元素:

...
case 'VA':
   selected.selectedIndex = 0;
   break;
// etc.

(假设这是一个单选择select元素)

我相信如果你设置selectedIndex为-1,它将不会留下任何选择

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/assign-the-select by value,你可以遍历这些值,或者使用qSA或jQuery或dojo等库来获取它。

<select id="state-select">
  <option value="1">NC</option>
  <option value="2">SC</option>
</select>
使用jQuery

// select SC
$( '#state-select' ).val( 2 ); 

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;
    }
}

尝试:

selected.selectedIndex = [Your index]

或选择。Value = [option Value]