代码:
var newSelect=document.createElement('select');
index=0;
var optn = document.createElement("option");
//langArray is an array that contains different items..the size
//is not fixed for this array.
for(element in langArray)
{
//Now i want to assign each item in langArray to each option tag
//will it be sumthng like "optn.options[index]=new Option("Sports", "sportsvalue", true, false);
//optn.accept(langArray[0]);
index++;
}
我试图用这种方式填充选项,但它不是很好,因为我不知道如何在JS中填充数组中的选项。我是否必须使用循环,或者是否可以将langArray赋值给select元素的某个属性,然后所有内容都将启动并运行?
发布于 2011-07-07 02:21:51
您可以在循环中创建选项;
for(element in langArray)
{
var opt = document.createElement("option");
opt.value= index;
opt.innerHTML = element; // whatever property it has
// then append it to the select element
newSelect.appendChild(opt);
index++;
}
// then append the select to an element in the dom
发布于 2011-07-07 02:21:34
您需要在循环中创建option
元素,设置属性和文本,并将其附加到select
元素:
var select = document.createElement('select'),
option,
i = 0,
il = langArray.length;
for (; i < il; i += 1) {
option = document.createElement('option');
option.setAttribute('value', langArray[i].value);
option.appendChild(document.createTextNode(langArray[i].text));
select.appendChild(option);
}
这里假设你的langArray
看起来像这样:
var langArray = [
{value: "val1", text: "text 1"},
{value: "val2", text: "text 2"}
];
您需要调整代码以匹配您的数组
发布于 2019-02-25 18:00:16
var dynamicSelect = document.getElementById("selectID");
langArray.forEach(function(item){
{
var newOption = document.createElement("option");
newOption.text = item.toString();//item.whateverProperty
dynamicSelect.add(newOption);
//new select items should populated immediately
});
https://stackoverflow.com/questions/6601028
复制相似问题