我通过观看很多教程创建了这个购物车。现在我来从购物车中删除一个项目。如果有人可以帮助我,我将不胜感激。
//add item to cart
(function(){
const cartbtn = document.querySelectorAll(".add_to_cart_button");
cartbtn.forEach(function(btn) {
btn.addEventListener("click", function(event){
if (event.target.parentElement.classList.contains("add_to_cart_button"))
{
let fullpath = event.target.parentElement.previousElementSibling.children[0].children[0].src;
const item = {};
item.img = fullpath;
let name = event.target.parentElement.previousElementSibling.children[3].children[0].textContent;
item.name = name;
let price = event.target.parentElement.previousElementSibling.children[3].children[1].textContent;
let finalprice = price.slice(1).trim( );
item.price = finalprice;
//console.log(item);
const cartitem = document.createElement('li');
cartitem.classList.add("clearfix");
cartitem.innerHTML =
`
<img src="${item.img}" alt="item1" />
<span class="item-name">${item.name}</span>
<span class="item-price">${item.price}$</span>
<span class="item-quantity"> <a href="#/" />Delete</span>
`;
const cart = document.getElementById("cartitem");
const insert =document.querySelector("insert");
cart.insertBefore(cartitem,insert);
showtotal();
}
});
});
function showtotal(){
const total =[];
const items = document.querySelectorAll(".item-price");
items.forEach(function(item){
total.push(parseFloat(item.textContent));
});
const totalmoney=total.reduce(function(total,item){
total += item;
return total;
},0);
const finalmoney = totalmoney.toFixed(2);
document.getElementById("totalitem").textContent=total.length;
document.getElementById("totalitems").textContent=total.length;
document.querySelector(".main-color-text").textContent = finalmoney ;
}
})();
答案 0 :(得分:1)
在代码行,
<a href="#/" />Delete</span> // Also, do not forget to close Anchor Link tags
您可以在这些Delete
按钮上添加课程,
<a href="#/" class="remove-item-from-cart">Delete</a>
页面完全加载后,在remove-item-from-cart
类中添加一个事件,并在事件监听器中,使用一些JavaScript通过检查事件变量从购物车中删除项目。