1

我想用动态值填充我的下拉列表,但列表仍然为空,换句话说,没有显示任何选项有人能帮帮我吗!!!这是我的代码http://jsfiddle.net/n6ahz/24/

var newdiv = document.createElement('div');
var text="TEXT";
var n=0;
newdiv.innerHTML += "<br> Question " + (n) + " : " + text + " ? <br><br>";
var m = 0;

var options = '';
for (var j = 1; j < 5; j++) {
 var val = "marwa" + j;
if (val) {
    m++;
    options += " <option value="+j+"> " + val + "</option>";
     }
 }
 newdiv.innerHTML += "<select name='single' id='single'>";
 newdiv.innerHTML += " "+options + " </select> ";

document.getElementById('results').appendChild(newdiv);​
4

3 回答 3

7

代替

newdiv.innerHTML += "<select name='single' id='single'>";
newdiv.innerHTML += " "+options + " </select> ";

尝试

newdiv.innerHTML += "<select name='single' id='single'> "+options + " </select> ";

我认为一次添加一点 HTML 是行不通的,因为浏览器会尝试立即呈现它。

于 2012-06-01T15:04:59.273 回答
4

With innerHTML, the actual DOM gets updated everytime you make a change. So you can't reliably make piecemeal changes like you're doing. Create a variable like var html and save all your HTML updates into it, then set element.innerHTML = html.

var newdiv = document.createElement('div');
var html = "";
var text="TEXT";
var n=0;
html += "<br> Question " + (n) + " : " + text + " ? <br><br>";
var m = 0;

var options = '';
for (var j = 1; j < 5; j++) {
 var val = "marwa" + j;
 if (val) {
    m++;
    options += " <option value="+j+"> " + val + "</option>";
 }
}
html += "<select name='single' id='single'>";
html += " "+options + " </select> ";
newdiv.innerHTML = html;

document.getElementById('results').appendChild(newdiv);​
于 2012-06-01T15:07:43.577 回答
1
var newdiv = document.createElement('div');
var text="TEXT";
var n=1;
newdiv.innerHTML += "<br> Question " + (n) + " : " + text + " ? <br><br>";
var m = 1;

var options = '';
for (var j = 0; j <= 5; j++) {
     var val = "marwa" + j;
if (val) {
        m++;
        options += " <option value="+j+"> " + val + "</option>";
         }
    }
newdiv.innerHTML += "<select name='single' id='single'  "+options + " </select> ";

document.getElementById('results').appendChild(newdiv);​
于 2012-06-01T15:18:10.547 回答