如何在javascript中填充select元素的选项 [英] How to populate the options of a select element in javascript
本文介绍了如何在javascript中填充select元素的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码:
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元素的某些属性,并且每个东西都将启动并运行?
I'm trying to get options populated by this way but its not coming all right as I don't know how to populate the options from an array in JS. Do I even have to use the loop or can I just assign the langArray to some property of select element and every thing will be up and running?
推荐答案
您可以在循环中创建选项;
You can create the option inside the loop;
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
这篇关于如何在javascript中填充select元素的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文