[英]JavaScript seeting selectedIndex to be blank for select do not work
I am trying to make default selection of a dropdown selection to be blank. 我试图将下拉选择的默认选择设置为空白。
If I generate a select dropdown with HTML, it works. 如果我使用HTML生成选择下拉列表,则可以正常工作。 However when I generate the same dropdown with javascript, it does not work.
但是,当我使用javascript生成相同的下拉列表时,它不起作用。
Please see http://jsfiddle.net/m2HSb/ 请参阅http://jsfiddle.net/m2HSb/
<select id="myDropdown">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
<div id="yo"></div>
document.getElementById("myDropdown").selectedIndex = -1
var my_select = document.createElement("select")
for ( var i = 0 ; i < 3 ; i++ ) {
my_select.options[i] = new Option(i,i)
}
my_select.selectedIndex = -1
document.getElementById("yo").appendChild(my_select)
Note that the first dropdown is blank, and the second is not. 请注意,第一个下拉列表是空白,第二个下拉列表是空白。
Apparently you can't set the selectedIndex
of a select
element that hasn't been inserted into the DOM yet. 显然你不能设置尚未插入DOM的
select
元素的selectedIndex
。
If you move my_select.selectedIndex = -1
after the append
then it works fine. 如果在
append
后移动my_select.selectedIndex = -1
,那么它可以正常工作。
var my_select = document.createElement("select");
for ( var i = 0 ; i < 3 ; i++ ) {
my_select.options[i] = new Option(i,i);
}
document.getElementById("yo").appendChild(my_select);
my_select.selectedIndex = -1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.