[英]what is the best way to write a for in loop to the page
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>')
}
I want to know what the best way to insert this into the DOM instead of logging it to the console. 我想知道什么是将其插入DOM而不是将其记录到控制台的最佳方法。 I want to use just JavaScript
我只想使用JavaScript
Depends on what is already in the HTML. 取决于HTML中已有的内容。 If you're simply adding exactly what you have, it wouldn't be a bad idea to just use:
如果您只是简单地添加自己拥有的东西,那么使用它并不是一个坏主意:
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;
where "main_ul" is: 其中“ main_ul”是:
<ul id="main_ul"></ul>
Another option is: 另一个选择是:
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);
}
Something you might look at to help decide which to use: "innerHTML += ..." vs "appendChild(txtNode)" 您可能会看一些东西来帮助决定使用哪个: “ innerHTML + = ...” vs“ appendChild(txtNode)”
Native, cross-browser DOM methods are the safest. 本地的跨浏览器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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.