简体   繁体   中英

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()

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.

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.

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.

Now you can use all of these to write a document.onload function that will use the render function with whatever parameters you want.

ps: localStorage does not work with stack snippets, so I copy/pasted and tested in 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.

This way you can just call in displayCart() this.item and you will have all the elements.

Retrieve the item inside the loadCart function & on each iteration pass the element.

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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