当我单击fa-times图标时,我试图能够从购物车页面中删除一项。我使用本地存储来添加项目,因此不确定是否应该使用它来删除它们。 displaycart()函数位于代码的底部。我不确定是否应该在此应用代码,也可以谢谢。
var products = [
{
name: "Red Shirt",
tag: "topimg-0",
price: 30,
inCart: 0,
},
{
name: "Black-hoodie",
tag: "topimg-1",
price: 60,
inCart: 0,
},
{
name: "Gray-hoodie",
tag: "topimg-2",
price: 60,
inCart: 0,
},
];
for (let i = 0; i < cartbtns.length; i++) {
cartbtns[i].addEventListener("click", () => {
cartNumbers(products[i]);
totalCost(products[i]);
});
}
function onLoadCartNumbers() {
var productNumbers = localStorage.getItem("cartNumbers");
if (productNumbers) {
document.querySelector(".cart span").textContent = productNumbers;
}
}
function cartNumbers(products) {
var productNumbers = localStorage.getItem("cartNumbers");
productNumbers = parseInt(productNumbers);
if (productNumbers) {
localStorage.setItem("cartNumbers", productNumbers + 1);
document.querySelector(".cart span").textContent = productNumbers + 1;
} else {
localStorage.setItem("cartNumbers", 1);
document.querySelector(".cart span").textContent = 1;
}
setItems(products);
}
function setItems(products) {
var cartItems = localStorage.getItem("productsInCart");
cartItems = JSON.parse(cartItems);
console.log("My cart items are", cartItems);
if (cartItems != null) {
if (cartItems[products.tag] == undefined) {
cartItems = {
...cartItems,
[products.tag]: products,
};
}
cartItems[products.tag].inCart += 1;
} else {
products.inCart = 1;
cartItems = {
[products.tag]: products,
};
}
localStorage.setItem("productsInCart", JSON.stringify(cartItems));
}
function totalCost(products) {
// console.log("the product price is", products.price);
let cartCost = localStorage.getItem("totalCost");
console.log("mycartCost is ", cartCost);
if (cartCost == null) {
//
localStorage.setItem("totalCost", products.price);
} else {
cartCost = parseInt(cartCost);
localStorage.setItem("totalCost", cartCost + products.price);
}
}
function displayCart() {
var cartItems = localStorage.getItem("productsInCart");
cartItems = JSON.parse(cartItems);
var productContainer = document.querySelector(".products");
let cartCost = localStorage.getItem("totalCost");
console.log(cartItems);
if (cartItems && productContainer) {
productContainer.innerHTML = "";
Object.values(cartItems).map((item) => {
productContainer.innerHTML += `
<div class="product">
<i class="fa fa-times-circle remove" ></i>
<img src="./images/${item.tag}.jpg">
<span>${item.name}</span>
</div>
<div class="item-price">$${item.price}.00</div>
<div class="item-quantity">
<i class="fas fa-caret-left decrease"></i>
<span>${item.inCart}</span>
<i class="fas fa-caret-right increase" ></i>
</div>
<div class="item-total">
$${item.inCart * item.price}.00
</div>
`;
});
productContainer.innerHTML += `
<div class="basketTotalContainer">
<h4 class="basketTotalTitle">
Basket Total:
</h4>
<h4 class="basketTotal">$${cartCost}.00</h4>
</div>
`;
}
var removeBtn = document.getElementsByClassName(".remove");
}
onLoadCartNumbers();
displayCart();