Javascript localStorage循环只输出最后一项

时间:2015-08-22 09:56:43

标签: javascript jquery loops for-loop local-storage

您好我的javascript for循环有问题,我在localStorage中有2个项目:

{"nazev":"1","sire":"2","mnozstvi":"3","barva":"4","typ":"5","slozeni":"6","strec":"7","poznamka":"8"}
{"nazev":"9","sire":"10","mnozstvi":"11","barva":"12","typ":"13","slozeni":"14","strec":"15","poznamka":"16"}

我的代码:

if(window.localStorage.length > 0) {
    for (var i = 0, len = localStorage.length; i < len; i++) {
        var foo = localStorage.getItem(localStorage.key(i));
    }
    //con
    $('#nv').html(foo);
}

和html输出(console.log输出两者;但这不是):

{"nazev":"9","sire":"10","mnozstvi":"11","barva":"12","typ":"13","slozeni":"14","strec":"15","poznamka":"16"}

如果有人知道它为什么会发生以及如何解决它:/

3 个答案:

答案 0 :(得分:1)

<meta property="og:type" content="website" />

答案 1 :(得分:1)

代码正在写你要求的最后一个,你可以累积然后打印; photo = models.ImageField(upload_to='images')

foo +=

答案 2 :(得分:1)

在你的代码中,foo取最后一个值,你需要在for循环中连接它。我假设你早些时候已经初步化了。

if(window.localStorage.length > 0) {
for (var i = 0, len = localStorage.length; i < len; i++) {
    var foo+ = localStorage.getItem(localStorage.key(i)); //concate the string
}
    $('#nv').html(foo);
}