我有以下 html 代码,我试图通过 selectedIndex 设置选项的值。问题是该选项仍然显示旧值,而如果我对所选内容发出警报,它会给我正确的答案。
我错过了什么?
<select name="select-choice-1" id="select-choice-1">
<option value="none">Choose One</option>
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
<option value="4">d</option>
</select>
<script>
var HomeLocation = 1;
document.getElementById("select-choice-1").selectedIndex = HomeLocation;
alert(document.getElementById("select-choice-1").selectedIndex); // shows 1
</script>
最佳答案
我的浏览器行为不一致。我通常必须设置 selectedIndex
并设置selected
<option>
的属性(property):
var select = document.getElementById("select-choice-1");
select.selectedIndex = 1;
select.options[1].selected = true;
关于Javascript 选择索引值不改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26652518/