我想用动态值填充我的下拉列表,但列表仍为空,换句话说没有显示选项可以有人帮助我!!! 这是我的代码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);
答案 0 :(得分:7)
而不是
newdiv.innerHTML += "<select name='single' id='single'>";
newdiv.innerHTML += " "+options + " </select> ";
试
newdiv.innerHTML += "<select name='single' id='single'> "+options + " </select> ";
我不认为一次添加HTML有效,因为浏览器会尝试立即呈现它。
答案 1 :(得分:4)
使用innerHTML
,每次进行更改时,实际的DOM都会更新。因此,您无法像您一样可靠地进行零碎的更改。创建一个像var html
这样的变量并将所有HTML更新保存到其中,然后设置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);
答案 2 :(得分: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);