For循环数组只显示最后一个值 [英] For loop through Array only shows last value
本文介绍了For循环数组只显示最后一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试遍历一个数组,然后使用 innerHTML 为数组中的每个条目创建一个新的
I'm trying to loop through an Array which then uses innerHTML to create a new
window.onload = function() {
// Read value from storage, or empty array
var names = JSON.parse(localStorage.getItem('locname') || "[]");
var i = 0;
n = (names.length);
for (i = 0; i <= (n-1); i++) {
var list = names[i];
var myList = document.getElementById("list");
myList.innerHTML = "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
}
}
我的 HTML 中有一个带有 id 'list' 的 UL.
I have a UL with the id 'list' in my HTML.
推荐答案
改变你的 for
循环:
for (i = 0; i <= (n-1); i++) {
var list = names[i];
var myList = document.getElementById("list");
myList.innerHTML += "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
}
使用 +=
而不是 =
.除此之外,您的代码看起来不错.
Use +=
instead of =
. Other than that, your code looks fine.
这篇关于For循环数组只显示最后一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文