2013-03-26 89 views
0

我想使默認選擇的下拉選擇爲空。JavaScript selections selectedIndex空白選擇不工作

如果我使用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) 

注意,第一個下拉列表是空的,第二個是沒有的。

+3

你討厭分號嗎? – 2013-03-26 21:02:52

+0

它沒有區別,對吧? – user1486030 2013-03-26 21:16:32

+0

它通常沒有區別。結果是人們不同意他們的用法。 – Jivings 2013-03-26 21:17:50

回答

2

顯然,您不能設置select元素的selectedIndex還沒有插入到DOM中。

如果你移動my_select.selectedIndex = -1append然後它工作正常。

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; 

Here's the fiddle