我想确保我在此函数中创建的选项元素的值为0,1,2,3,4 ... ..因此它们与索引号匹配。我只是不确定如何在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 :(得分:0)
如何确保将option.value
设为“i”?
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 ...
}
答案 1 :(得分: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 );
}
}