简体   繁体   English

如何从阵列中检索和显示本地存储中的数据?

[英]How to retrieve and display data in local storage from an array?

How do I get the item.title, item.price, item.imageScr values and set them to variables I can use in displayCart() 如何获取item.title,item.price,item.imageScr值并将它们设置为可在displayCart()使用的变量

I am saving an array of information with those three values with the key item. 我正在将带有这三个值的信息数组与关键项一起保存。 but I want to display that information in my shopping cart. 但我想在我的购物车中显示该信息。 And i don't know in what way how to display that information and pass it in to display cart. 而且我不知道该如何显示该信息并将其传递给购物车。

var product = [
  {
    title: title,
    price: price,
    image: imageSrc
  }
];
var pods = JSON.parse(localStorage.getItem("item")) || [];
pods.push(product);
localStorage.setItem("item", JSON.stringify(pods));
//displayCart(title, price, imageSrc)
saveCart();

function loadCart() {
  for (var i = 0; i < localStorage.length; i++) {
    displayCart();
  }
}

function displayCart() {
  //var item = JSON.parse(localStorage.getItem("item"))[0]
  var cartRow = document.createElement("div");
  cartRow.classList.add("cart-row");
  var cartItems = document.getElementsByClassName("cart-items")[0];
  var cartRowContents = `
        <div class="cart-row">
  <div class="cart-column cart-item" style="padding-top: 1%">
    <img class="image" style="width: 25%;" src="${imageSrc}" alt="" />
    <h2 style="padding-left: 5%">${title}</h2>
  </div>
  <div class="cart-column cart-price" style="padding-top: 1%">
    <h2 class="price">${price}</h2>
  </div>
  <form class="cart-column cart-quantity">
    <input
      class="quantity"
      type="number"
      id="number"
      value="1"
      style="width: 15%; margin-left: auto; margin-right: 60%"
    />
  </form>
  <span style="margin-top: auto; margin-bottom: auto;">
    <button class="btn btn-primary shop-item-button " type="button">
      Remove
    </button>
  </span>
</div>`;

  cartRow.innerHTML = cartRowContents;
  cartItems.append(cartRow);
  cartRow
    .getElementsByClassName("btn-primary")[0]
    .addEventListener("click", RemoveCartItem);
  saveCart();
}

I would assume I could just get the item.value and use that as a reference to displaying the price,title and image but that doesn't work. 我假设我可以只获取item.value并将其用作显示价格,标题和图像的参考,但这是行不通的。

Example of what I meant in my comments. 我在评论中表示的示例。 Apart from the selectors, we pass in all the relevant data into the function. 除了选择器之外,我们还将所有相关数据传递到函数中。

So the render() function takes the collection it has to render, the place where it has to render, and an extra. 因此render()函数采用必须渲染的集合,必须渲染的位置以及其他内容。

The event handlers take in the event object. 事件处理程序接受事件对象。

You notice that the functions that do not take parameters, fetch_cart(), is a function that actually returns something. 您会注意到,不带参数的函数fetch_cart()是实际上返回某些内容的函数。

Now you can use all of these to write a document.onload function that will use the render function with whatever parameters you want. 现在,您可以使用所有这些来编写document.onload函数,该函数将使用render函数和所需的任何参数。

ps: localStorage does not work with stack snippets, so I copy/pasted and tested in chrome. ps:localStorage不适用于堆栈片段,因此我在chrome中复制/粘贴并进行了测试。

 const stock = [ { "id": 1, "title": "shoes", "price": 99.99, "image": "/path/1.png", "available": 75 }, { "id": 2, "title": "shirt", "price": 67.14, "image": "/path/2.png", "available": 2 }, { "id": 3, "title": "shoes", "price": 85.25, "image": "/path/3.png", "available": 0 }, { "id": 4, "title": "hats", "price": 15.2, "image": "/path/4.png", "available": 18 } ]; const render = ( collection, list, button_type ) => { const items = collection.map( item => ` <li> <span>${ item.title }</span> <span>${ item.price }</span> <span>${ item.available }</span> <button data-type="${ button_type }" data-reference="${ item.id }">${ button_type }</button> </li> `); list.innerHTML += items.join( '' ); }; const fetch_cart = () => { return Array.from({ length: localStorage.length - 1 }, ( _, index ) => { const item_key = localStorage.key( index ); return JSON.parse( localStorage.getItem( item_key )); }); }; const add_to_cart = event => { const id = parseInt( event.target.getAttribute( 'data-reference' ), 10 ); const item = stock.find( item => item.id === id ); if ( !item.available > 0 ) alert( 'item is sold out' ); else { item.available -= 1; const clone = Object.assign({}, item ); localStorage.setItem( `order_${ Date.now() }`, JSON.stringify( clone )); render( [ clone ], list_cart, 'delete' ); } }; const delete_from_cart = event => { console.log( 'TODO' ); // basically the reverse of add_to_cart }; const list_stock = document.querySelector( '#stock' ); const list_cart = document.querySelector( '#cart' ); list_stock.addEventListener( 'click', add_to_cart ); list_cart.addEventListener( 'click', delete_from_cart ); render( stock, list_stock, 'add' ); render( fetch_cart(), list_cart, 'delete' ); 
 ul { border: 1px solid grey; margin-bottom: 20px; } 
 <label>Your order</label> <ul id="cart"></ul> <label>Available</label> <ul id="stock"></ul> 

You can save the items in a this variable. 您可以将项目保存在此变量中。 As soon as you save the element item.title etc. just save them as this.item.title. 一旦保存元素item.title等,就将其另存为this.item.title。

This way you can just call in displayCart() this.item and you will have all the elements. 这样,您可以只在displayCart()this.item中调用,您将拥有所有元素。

Retrieve the item inside the loadCart function & on each iteration pass the element. 检索loadCart函数中的项目,并在每次迭代时传递元素。

 function loadCart() {
    let lcStr = JSON.parse(localStorage.getItem('itemName'));
    for (var i = 0; i < lcStr.length; i++){
        displayCart(lcStr[i]);
    }
  }

You need to make slight change in the displayCart function 您需要在displayCart功能中进行一些更改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM