代码:
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元素的某些属性,并且每个东西都将启动并运行?
您可以在循环内创建选项;
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
您需要在循环中创建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"}
];
您需要调整代码以匹配您的阵列
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
});
脏选项是使用div并根据先前的选择填充选择字符串(innerHTML)。您仍然可以使用上面提到的langArray。