首页 文章

如何从此购物车中删除商品?

提问于
浏览
2

我通过观看大量的教程创建了这个购物车 . 现在我来取消购物车中的商品 . 如果有人可以帮助我,我真的很感激 .

//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 ;
        }
})();

1 回答

  • 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从购物车中删除项目 .

相关问题