HTML5本地存储JSON多个对象 [英] HTML5 local storage JSON multiple objects
问题描述
有没有人知道,当我在javascript中进行循环时,是否可以在其中创建包含多个对象的本地存储?
Does anyone know, if it's possible to make a local storage with multiple objects in it when I'm doing a loop in javascript?
目前我的代码看起来像这样:
At the moment my code looks like this:
var albums = '';
var album_list = '';
$.each(data, function(i,item){
var name = item.name;
albums += '<li>'+item.name+'</li>';
var album_content = {name: item.name, uid: 1};
var album_content = album_content+',';
album_list += album_content;
});
var album_list = '['+album_list+']';
localStorage.setItem("albums", JSON.stringify(album_list));
var albums_l = JSON.parse(localStorage.getItem("albums"));
$.each(albums_l, function(i,item){
console.log(item.name);
});
但这给了我一个错误。
任何人都有更好的解决方案,所以我只有一个本地存储及其中的所有数据?
But that gives me an error. Anyone have a better solution for this, so I just have one localstorage and all the data in that?
推荐答案
您在代码中混合对象和字符串。您的 album_content
在循环中初始化为对象( {name:item.name,uid:1}
)。在下一行中,您可以通过附加逗号将其视为字符串。
You're mixing objects and strings in your code. Your album_content
is initialized in the loop as an object ({name: item.name, uid: 1}
). In the very next line you treat it as a string by appending a comma.
总体使用数组来收集所有对象。 (几乎)总是更好地使用本机对象而不是尝试以某种方式模拟它们。
Overall use an array to collect all your objects. It's (almost) always better to use the native objects instead of trying to emulate them in some way.
请尝试使用此代码。
var albums = '';
var album_list = [];
$.each(data, function(i,item){
var name = item.name;
albums += '<li>'+item.name+'</li>';
var album_content = {name: item.name, uid: 1};
// remove that line completly
// var album_content = album_content+',';
album_list.push( album_content );
});
localStorage.setItem("albums", JSON.stringify( album_list ));
var albums_l = JSON.parse(localStorage.getItem("albums"));
$.each(albums_l, function(i,item){
console.log(item.name);
});
这篇关于HTML5本地存储JSON多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!