如何将本地存储放在DOM -JavaScript上
我遇到的问题是,当我循环通过本地存储时,只有最后一个物品放置在DOM上时,我想放置所有项目进行DOM
function checkStorage() {
let cartContents = document.getElementsByClassName("products")[0];
let cartProduct = document.createElement("div");
cartProduct.classList.add("product");
let cartCheck = JSON.parse(localStorage.getItem("localItem"));
// return cartCheck;
savedCart = "";
if (cartCheck === null) {
return;
} else {
console.log(cartCheck);
for (const check in cartCheck) {
if (Object.hasOwnProperty.call(cartCheck, check)) {
const element = cartCheck[check];
savedCart = `<img width="60" src="${element.img}" alt="iphone" />
<div>
<span class='title'> ${element.title}</span>
<div class='price-section'>
<input type="number" value="1" class="cart-quantity-input" />
<span class='cart-price'>${element.price}</span>
</div>
</div>
<button class='btn-danger'>
<i class="bi bi-x"></i>
</button>`;
cartProduct.innerHTML = savedCart;
console.log(cartProduct);
cartContents.append(cartProduct);
}
}
}
}
My problem I am having is when I loop through my local storage only the last item get place on the DOM when I want to place all items to do the DOM
function checkStorage() {
let cartContents = document.getElementsByClassName("products")[0];
let cartProduct = document.createElement("div");
cartProduct.classList.add("product");
let cartCheck = JSON.parse(localStorage.getItem("localItem"));
// return cartCheck;
savedCart = "";
if (cartCheck === null) {
return;
} else {
console.log(cartCheck);
for (const check in cartCheck) {
if (Object.hasOwnProperty.call(cartCheck, check)) {
const element = cartCheck[check];
savedCart = `<img width="60" src="${element.img}" alt="iphone" />
<div>
<span class='title'> ${element.title}</span>
<div class='price-section'>
<input type="number" value="1" class="cart-quantity-input" />
<span class='cart-price'>${element.price}</span>
</div>
</div>
<button class='btn-danger'>
<i class="bi bi-x"></i>
</button>`;
cartProduct.innerHTML = savedCart;
console.log(cartProduct);
cartContents.append(cartProduct);
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在更新
cartproduct
的整个innerhtml
,用于循环内部的每个迭代。这就是为什么只有最后一项被放在DOM上的原因。在循环外部创建一个空字符串,并在每个迭代中将HTML附加到该字符串。然后在循环之后更新
innerhtml
。You're updating the entire
innerHTML
ofcartProduct
for every iteration inside your for-loop. That's why only the last item gets put on the DOM.Create an empty string outside the for-loop, and append HTML to that string for every iteration. Then update the
innerHTML
after your for-loop.