有谁知道,如果有可能,使与它的多个对象的本地存储,当我做在JavaScript中循环?
目前我的代码看起来是这样的:
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);
});
但是,这给了我一个错误。 任何人对此有一个更好的解决办法,所以我只是有一个localStorage的和所有的数据吗?
你在你的代码混合对象和字符串。 您的album_content
在回路为对象初始化( {name: item.name, uid: 1}
在非常下一行,你把它当作附加一个逗号的字符串。
总体使用数组来收集所有对象。 这是(几乎)总是更好地使用,而不是试图模仿他们以某种方式的本地对象。
试试这个代码,而不是。
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);
});
怎么了:
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};
// at this point album_content is an object.. so it will be this string afterwards: "[object Object],"
var album_content = album_content+',';
album_list += album_content; //you're adding "[object Object],"
});
// album_list will now look like this: '["[object Object],[object Object],"]'
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);
});
如何做正确的:
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};
album_list.push(album_content);
});
localStorage.setItem("albums", JSON.stringify(album_list));
var albums_l = $.parseJSON(localStorage.getItem("albums"));
$.each(albums_l, function(i,item){
console.log(item.name);
});