对于通过数组循环只显示最后一个值

问题描述:

我是通过一个数组,然后使用innerHTML来为数组中的每个条目创建一个新的

  • 元素试图循环。不知怎的,我的code仅显示从数组的最后一个值。我一直停留在这几个小时,似乎无法找出我做错了什么。

    I'm trying to loop through an Array which then uses innerHTML to create a new

  • element for every entry in the array. Somehow my code is only showing the last value from the array. I've been stuck on this for a few hours and can't seem to figure out what I'm doing wrong.
    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 />";
        }
    }
    

    我有一个UL在我的HTML中的id'名单。

    I have a UL with the id 'list' in my HTML.

  • 更改循环:

    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 />";
    }
    

    使用 + = ,而不是 = 。除此之外,您的code看起来不错。

    Use += instead of =. Other than that, your code looks fine.