Javascript 尝试用选项填充下拉列表。只存储一个值
我正在运行以下脚本:Javascript 尝试用选项填充下拉列表。只存储一个值,javascript,jquery,html,drop-down-menu,Javascript,Jquery,Html,Drop Down Menu,我正在运行以下脚本: 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)
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);
}
函数插入格式(格式){
//删除下拉列表的内容(如果有)
document.getElementById('format').options.length=50;
//使用关联数组填充下拉列表
for(格式中的var键)
var newOption=“”+格式[键]+”;
$(“#格式”).append(newOption);
}
要填充以下内容,请选择:
<select id="format"></select>
但是,仅存储数组的最后一个元素。在调试模式下,似乎每次循环完成时下拉列表都会被覆盖,而不是添加新元素。当前应用的
代码不是内部循环
,因此只有最后一个值
被添加到下拉列表中。像这样改变你的循环
for (var key in formats)
{
var newOption = "<option value='"+key+"'>"+formats[key]+"</option>";
$("#format").append(newOption);
}
for(格式中的变量键)
{
var newOption=“”+格式[键]+”;
$(“#格式”).append(newOption);
}
当前应用的代码不是内部循环
,因此只有最后一个值
被添加到下拉列表中。像这样改变你的循环
for (var key in formats)
{
var newOption = "<option value='"+key+"'>"+formats[key]+"</option>";
$("#format").append(newOption);
}
for(格式中的变量键)
{
var newOption=“”+格式[键]+”;
$(“#格式”).append(newOption);
}
使用此代码
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);
}
}
函数插入格式(格式){
//删除下拉列表的内容(如果有)
document.getElementById('format').options.length=50;
//使用关联数组填充下拉列表
for(格式中的var键){
var newOption=“”+格式[键]+”;
$(“#格式”).append(newOption);
}
}
使用此代码
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);
}
}
函数插入格式(格式){
//删除下拉列表的内容(如果有)
document.getElementById('format').options.length=50;
//使用关联数组填充下拉列表
for(格式中的var键){
var newOption=“”+格式[键]+”;
$(“#格式”).append(newOption);
}
}