2011-07-06 66 views
17

代码:如何填充一个选择元素的选项在JavaScript

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元素的某个属性,并且每件事情都会启动并运行?

回答

27

您可以在循环内创建选项;

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 
+1

非常感谢lbu ...我认为这不应该是'newSelect.appendChild(opt)'你不觉得吗? 'newSelect.append(opt);'没有为我工作! – samach

+0

感谢您的更正 – Ibu

11

您需要创建循环内的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"} 
]; 

您需要调整代码以匹配您的阵列

相关问题