繁体   English   中英

JavaScript seeting selectedIndex为空白以供选择不起作用

[英]JavaScript seeting selectedIndex to be blank for select do not work

我试图将下拉选择的默认选择设置为空白。

如果我使用HTML生成选择下拉列表,则可以正常工作。 但是,当我使用javascript生成相同的下拉列表时,它不起作用。

请参阅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)

请注意,第一个下拉列表是空白,第二个下拉列表是空白。

显然你不能设置尚未插入DOM的select元素的selectedIndex

如果在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM