Как получить сохраненные элементы в localStorage из массива - PullRequest
0 голосов
/ 05 декабря 2018

У меня есть простая корзина покупок, которую я сохранил в localStorage с помощью функции карты, которая была предложена онлайн-ресурсом, но сейчас я не знаю, как получить эти элементы из localStorage и добавить ее в переменную.извините, если вам было легко, ребята, но я новичок в программировании.

function additemtocard(title, price, imgsrc) {
    let div = document.createElement('div');
    div.classList.add('each-cart-row');
    let mainElement = document.querySelectorAll('.cart-layout')[0];
    let carttitle = mainElement.querySelectorAll('.title');
    for(let i = 0; i < carttitle.length; i++){
        if(carttitle[i].innerText == title){
            alert('this item is on the cart');
        return;
        };
    }
    let tag = '<h4 class="title">'+(title)+'</h4><span class="price">'+(price)+'</span><h5 class="qty">1</h5><button class="removebtn">remove</button>';
    let cartlayout = document.querySelector('.added-product');
    div.innerHTML = tag;
    cartlayout.appendChild(div); 
    div.querySelectorAll('.removebtn')[0].addEventListener('click', removebtncart);      
}


function savecart(){
    let qty = document.querySelector('.totalqty').textContent;
    let tprice = document.querySelector('.total-layout span').textContent;
    let listitem = document.querySelectorAll('.each-cart-row');
    let m = [...listitem].map(function(item) {
      return {
        text: item.querySelector('.title').textContent.trim(),
        price: item.querySelector('.price').textContent.trim(),
      }
    })
    localStorage.setItem('qty', qty);
    localStorage.setItem('tprice', tprice);
    localStorage.setItem('layoutlist', JSON.stringify(m));
}


function loadcart() {
    let qty = localStorage.getItem('qty');
    let tprice = localStorage.getItem('tprice');
    let m = JSON.parse(localStorage.getItem('layoutlist'));
    document.querySelector('.totalqty').textContent = qty;
    document.querySelector('.total-layout span').textContent = tprice;

    // i need to get title & price from m variable and add it to below code
    document.querySelector('.title').textContent;
    document.querySelector('.price').textContent; 

}

HTML

<div class="cart-layout">
   <div class="added-product">
    <!-- Div with each-cart-row class should be added here each time button is clicked -->
   </div>
   <div class="total-layout">
       <h2>Total</h2>
       <span>$0</span>
   </div>
   <div class="added-cart-btn">
       <button id="removeall">Remove all</button>
       <button>Proceed</button>
   </div>
</div>

1 Ответ

0 голосов
/ 05 декабря 2018

Вы можете использовать цикл для ... из , чтобы перебирать элементы

function loadcart() {
    let qty = localStorage.getItem('qty');
    let tprice = localStorage.getItem('tprice');
    let m = JSON.parse(localStorage.getItem('layoutlist'));
    document.querySelector('.totalqty').textContent = qty;
    document.querySelector('.total-layout span').textContent = tprice;

// i need to get title & price from m variable and add it to below code

for(let item of m) { 
  document.querySelector('.title').textContent = item.text;
  document.querySelector('.price').textContent = item.price;
  }
}
...