2016-06-09 26 views
0

我運行此腳本:嘗試使用選項填充下拉菜單。只有一個值存儲

function insertformat(formats){ 
//Deletes the content of the dropdown if there was any 
     document.getElementById('format').options.length = 50; 
//fills the dropdown with an associative array 
     for (var key in formats) 
     var newOption = "<option value='"+key+"'>"+formats[key]+"</option>"; 
     $("#format").append(newOption); 
    } 

填寫以下選擇:

<select id="format"></select> 

但是隻存儲在陣列中的最後一個元素。在調試模式下,似乎每次循環完成時都會覆蓋下拉列表,而不是添加新元素。

回答

3

目前appned代碼不是inside loop所以只有last value被添加到下拉列表中。像這樣改變你的循環。

for (var key in formats) 
{  
var newOption = "<option value='"+key+"'>"+formats[key]+"</option>"; 
$("#format").append(newOption); 
} 
2

使用此代碼

function insertformat(formats){ 
     //Deletes the content of the dropdown if there was any 
     document.getElementById('format').options.length = 50; 
     //fills the dropdown with an associative array 
     for (var key in formats){ 
     var newOption = "<option value='"+key+"'>"+formats[key]+"</option>"; 
     $("#format").append(newOption); 
    } 
} 
相關問題