[英]Javascript getElementById overwriting issue
I have a simple question concerning Javascript. 我有一个关于Javascript的简单问题。 I am trying to print in a loop some values to div container.
我正在尝试将一些值循环打印到div容器中。 The problem is that instead printing the value several times in a loop, each time it is overwritten and as a result I get only one value.
问题是,每次循环重写该值几次,每次覆盖它一次,结果我只能得到一个值。 See the code below:
请参见下面的代码:
for (i=0; i<json.Locations.length; i++) {
var location = json.Locations[i];
var content = document.getElementById('eventsnearby');
var html = location.name;
content.innerHTML = html;
}
Any ideas welcomed. 任何想法都欢迎。 Thanks.
谢谢。
Append, don't assign. 追加,不分配。
content.innerHTML += html;
Better yet, use standard DOM. 更好的是,使用标准DOM。
var content = document.getElementById('eventsnearby');
for (var i = 0; i < json.Locations.length; i++) {
var text = json.Locations[i].name;
var node = document.createTextNode(text);
content.appendChild(node);
}
You only get one value because you're setting the innerHTML property during each loop iteration instead of appending to it. 您只能得到一个值,因为您是在每次循环迭代期间设置innerHTML属性,而不是附加到该属性。 Try using
content.innerHTML += html;
尝试使用
content.innerHTML += html;
. 。
for (i=0; i<json.Locations.length; i++) {
var location = json.Locations[i];
var content = document.getElementById('eventsnearby');
var html = location.name;
content.innerHTML += html;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.