2011-04-04 62 views
0

我想确保我在此函数中创建的选项元素的值为0,1,2,3,4 ...所以它们匹配索引号。我只是不确定如何在for循环中做到这一点。如何将增量值添加到我在for循环中创建的元素

任何帮助都会很棒。谢谢

function receiveAnswer(response) { 
    var aSeats = document.getElementById("aSeats"); 
    while (aSeats.childNodes.length > 0) { // clear it out 
    aSeats.removeChild(aSeats.childNodes[0]); 
    } 
    for (var i = 0; i < response.aSeats.length; i++) { // add the items back in 
    var option = aSeats.appendChild(document.createElement("option")); 
    option.appendChild(document.createTextNode(response.aSeats[i])); 
    } 
} 

回答

0

如何确保您将option.value设置为“我”?

for (var i = 0; i < response.aSeats.length; i++) { // add the items back in 
    var option = aSeats.appendChild(document.createElement("option")); 
    option.appendChild(document.createTextNode(response.aSeats[i])); 
    option.value = i; 
    // you need a line here to add the option to the <select> element ... 
    } 
+0

是啊,这正是我想要做的,但我是一个JavaScript的小白,所以我不知道如何正确地做到这一点 – novicePrgrmr 2011-04-05 00:03:33

+0

哇有没有一个很容易的按钮?非常感谢。我敢肯定,你认为我很密集,但感谢你的帮助! – novicePrgrmr 2011-04-05 00:07:33

+0

@Eric没问题,祝你好运! – Pointy 2011-04-05 00:18:36

0

您可以创建一个选择与Option构造一个选项:
new Option(text, value)

function receiveAnswer(response){ 
    var sel = document.getElementById('aSeats'); 
    // clear all current options 
    sel.length = 0; 
    // add new options 
    for(var i = 0; i < response.aSeats.length; i++) { 
     var opt = new Option(response.aSeats[i], i); 
     sel.appendChild(opt); 
    } 
} 
相关问题