取决于 HTML 中已有的内容。如果你只是简单地添加你所拥有的,那么使用它并不是一个坏主意:
var all_family = "";
for (var person in family) {
all_family += "<li>the " + person + " is a " + family[person] + "</li>";
}
document.getElementById("main_ul").innerHTML = all_family;
其中“main_ul”是:
<ul id="main_ul"></ul>
另一种选择是:
var ul = document.getElementById("main_ul");
for (var person in family) {
var li = document.createElement("li");
li.innerHTML = "the " + person + " is a " + family[person];
main_ul.appendChild(li);
}
您可能会看一些东西来帮助决定使用哪个:“innerHTML += ...”与“appendChild(txtNode)”