我有一个简单的购物车,使用在线资源建议的地图功能将其存储在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>
答案 0 :(得分:0)
您可以使用for...of循环遍历项目
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;
}
}