使用javascript添加下拉列表的选项

时间:2015-10-21 06:21:35

标签: javascript list drop-down-menu

我需要在下拉列表中添加选项。我在下拉列表中有一个包含所需选项的数组,但我不确定如何将数组附加到列表中

var productList = document.getElementById("selectFood");
var foodOption = document.createElement("option");

foodOption.textContent = [{ 
    option1: "Meat Lovers"
}, {
    option2: "Buffalo Wings"
}, {
    option3: "margherita"
}, {
    option4: "classic"
}];

for (i = 0; i < productList.length; i++) { 
    productList.appendChild(foodOption);
}

4 个答案:

答案 0 :(得分:0)

你可以使用jquery,

$.each(foodOption.textContent, function (i, value) {
    $('#selectFood').append($('<option>').text(value).attr('value',value));
});

答案 1 :(得分:0)

您需要创建一个选项元素。

for (i = 0; i < foodOption.textContent.length; i++) {
   var newElement = document.createElement('option');
   newElement.innerHTML = foodOption.textContent[i];
   productList.appendChild(newElement);
}

答案 2 :(得分:0)

你必须创建一个字符串数组而不是一个对象数组

试试这个

 foodOption.textContent = ["Meat Lovers" , "Buffalo Wings" , "margherita", "classic" ]


$.each(foodOption.textContent, function (index, value) {

    $('#selectFood').append($('<option/>', { value: value, text: value }));

});

答案 3 :(得分:-1)

尝试下面的解决方案代码。

var productList = document.getElementById("selectFood");
var textContent = [{ 
    option1: "Meat Lovers"
}, {
    option2: "Buffalo Wings"
}, {
    option3: "margherita"
}, {
    option4: "classic"
}];

for(var iIntex in textContent) {
    var foodOption = document.createElement("option");
    var option=textContent[iIndex]["option"+(iIndex+1)];
    foodOption.setAttribute("value",option);
    foodOption.innerHTML=option;
    productList.appendChild(foodOption);
}
相关问题