对于通过数组循环只显示最后一个值 [英] For loop through Array only shows last value

查看:804
本文介绍了对于通过数组循环只显示最后一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是通过一个数组,然后使用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.

    这篇关于对于通过数组循环只显示最后一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆