var family = {
dad: 'Father',
mom: 'Mother',
son: 'Boy',
daughter: 'Girl'
}
for ( var person in family ) {
console.log('<li>' + 'the ' + person + ' is a ' + family[person] + '</li>')
}
我想知道将这个插入DOM的最佳方法,而不是将其记录到控制台。我想只使用JavaScript
答案 0 :(得分:1)
取决于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 += ..." vs "appendChild(txtNode)"
答案 1 :(得分:0)
原生的,跨浏览器的DOM方法是最安全的。
var list = document.createElement('li');
for (var person in family)
list.appendChild(
document.createTextNode('the person is a ' + family[person]) );
document.body.appendChild( list );