如何在localStorage中保存对象列表

时间:2018-10-28 14:44:54

标签: javascript json html5 local-storage

我有一个要保存在本地存储中的购物车。我已经保存了不在对象内部的项目,但是我不知道如何保存对象列表。我认为这并不难,但是我找不到问题,而且我实际上是编程的新手,所以请原谅我的问题。下面的代码将详细说明。

// HTML代码//

<div class="added-product">
              <div class="each-cart-row">
                 <img class="image" src="./images/AMH010327_W-1-dresslink.jpg">
                 <h4 class="title">T-shirt</h4>
                 <span class="price">$19.99</span>
                 <h3>1</h3>
                 <button class="removebtn">remove</button>
              </div>
              <div class="each-cart-row">
                 <img class="image" src="./images/AMH010327_W-1-dresslink.jpg">
                 <h4 class="title">shirt</h4>
                 <span class="price">$14.99</span>
                 <h3>1</h3>
                 <button class="removebtn">remove</button>
              </div>
             </div>

//这是我的第一次尝试//

var listitem = document.querySelector('.each-cart-row').textContent;
  localStorage.setItem('layoutlist', listitem);
  console.log(localStorage);

and i got this

//然后我尝试了此代码//

var listitem = document.querySelectorAll('.each-cart-row').textContent;
    for(var i = 0; i < listitem.length; i++){
        var title = listitem[i];
        localStorage.setItem('layoutlist', title);
            console.log(localStorage);   
     }

and i got this

//最后我使用了JSON //

var listitem = document.querySelectorAll('.each-cart-row');
       var jsonstr = JSON.stringify(listitem);
        localStorage.setItem('layoutlist', jsonstr);
            console.log(localStorage);  

and I got this

1 个答案:

答案 0 :(得分:0)

使用querySelectorAll并在其上使用map创建一个对象数组,该数组将具有 img src和文本。然后使用JSON.stringify将其转换为字符串,因为本地存储只能保存字符串。

var listitem = document.querySelectorAll('.each-cart-row');
   //using spread operatot to use array method on collection
    let m = [...listitem].map(function(item) {
      return {
        img: item.querySelector('img').getAttribute('src'),
        text: item.querySelector('.title').textContent.trim() // remove white space
      }
    })
    localStorage.setItem('layoutlist', JSON.stringify(m));

HTML

<div class="added-product">
      <div class="each-cart-row">
        <img class="image" src="./images/AMH010327_W-1-dresslink.jpg">
        <h4 class="title">T-shirt</h4>
        <span class="price">$19.99</span>
        <h3>1</h3>
        <button class="removebtn">remove</button>
      </div>
      <div class="each-cart-row">
        <img class="image" src="./images/AMH010327_W-1-dresslink.jpg">
        <h4 class="title">shirt</h4>
        <span class="price">$14.99</span>
        <h3>1</h3>
        <button class="removebtn">remove</button>
      </div>
    </div>
相关问题