2016-06-09 54 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); 
    } 
}