HTML5 local storage JSON multiple objects

前端 未结 2 1659
天涯浪人
天涯浪人 2021-01-21 02:30

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:

2条回答
  •  [愿得一人]
    2021-01-21 02:58

    What's wrong:

    var albums = '';
    var album_list = '';
    
    $.each(data, function(i,item){
       var name = item.name;
       albums += '
  • '+item.name+'
  • '; 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); });

    How to do it correct:

    var albums = '';
    var album_list = [];
    
    $.each(data, function(i,item){
       var name = item.name;
       albums += '
  • '+item.name+'
  • '; 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); });

提交回复
热议问题