购物车删除列表同时更新总价

Shopping Cart Delete List To Also Update Total Price

我正在使用 JavaScript 制作一个带有购物车系统的网站。在观看了 YouTube 视频后(考虑到我的新手技能),我已经完成了大部分购物车并取得了相当大的成功。但是,我似乎无法在更新购物车的同时从购物车中删除产品列表。

这是我的 JavaScript 代码,用于从购物车中删除不更新总价的产品列表:

const removeBtn = document.querySelectorAll('.remove-product')
removeBtn.forEach (function (rBtn) {
    rBtn.addEventListener('click', function () {
        cartItem.remove();
    });
}); 

谁能帮我解决这个问题?如果能得到答案,将不胜感激...

这是我的 HTML、CSS 和我的 JS 的其余部分:

HTML:

    <!-- Navigation Bar -->
    <nav class="main-nav">

        <!-- Logo -->
        <a href="index.html" class="logo-link">
            <div class="logo animated fadeInLeft">
                <img src="../Media/Logo/logo-red.png" class="red">
                <img src="../Media/Logo/logo.png" class="normal">
            </div>
        </a>

        <!-- Desktop/ Normal Navigation Links -->
        <ul class="nav-links">
            <li class="animated fadeInRight">
                <a href="shop-creator.html">Creator</a>
            </li>
            <li class="animated fadeInRight">
                <a href="shop-men.html">Men</a>
            </li>
            <li class="animated fadeInRight">
                <a href="shop-women.html">Women</a>
            </li>
        </ul>

        <!-- All Smaller Icons Here -->
        <div class="nav-small">

            <!-- Search and Shop Icon-->
            <ul class="nav-icons">

                <!-- Icons -->
                <li class="animated fadeInRight" id="search-button">
                    <i class="fas fa-search"></i>
                </li>
                <li class="animated fadeInRight" id="cart-button">
                    <i class="fas fa-shopping-cart"><sup class="item-count">0</sup></i>
                </li>

                <!-- Search Bar -->
                <input type="text" placeholder="Search">

                <!-- Shopping Cart -->
                <div class="shop-cart">

                    <!-- No Products -->
                    <div class="cart-text no-product">
                        <h3> No products in cart. </h3>
                    </div>

                    <!-- Products -->
                    <ul class="cart-list">
                        <!-- List Items Added By Javascript Here -->
                    </ul>

                    <!-- Total Price -->
                    <div class="cart-text total-price">
                        <h3> [=11=] </h3>
                    </div>

                </div>

            </ul>

            <!-- Mobile/ Burger Navigation Links -->
            <div class="burger animated fadeInRight">
                <div class="line"></div>
                <div class="line"></div>
                <div class="line"></div>
            </div>

        </div>

    </nav>

     <section class="product-container">
        <div class="product-slider">
            <ul id="slide-1">
                <li class="item">
                    <div class="product-item">
                        <div class="product-image">
                            <img src="../Media/Clothes/creator/extendedplay.png" alt="">
                        </div>
                        <div class="product-text">
                            <h1> Extended Play </h1>
                            <h2> 0.69</h2>
                            <span class="product-button">Add to Cart</span>
                        </div>
                    </div>
                </li>
                <li class="item">
                    <div class="product-item">
                        <div class="product-image">
                            <img src="../Media/Clothes/creator/heartache.png" alt="">
                        </div>
                        <div class="product-text">
                            <h1> Heartache </h1>
                            <h2> 9.99</h2>
                            <span class="product-button">Add to Cart</span>
                        </div>
                    </div>
                </li>
                ... 
            </ul>
        </div>
    </section>

CSS:

/* Navigation Bar */

.main-nav {
    display: flex;   
    justify-content: space-around;
    align-items: center;
    height: fit-content;
    position: fixed;
    width: 100%;
    transition: ease-in 0.1s;
    z-index: 100;
    background-color: white;
    border-bottom: #d3d3d3 solid 1px;
    padding: 20 0;
}

/* Logo */

.logo {
    width: 130px;
    margin-left: 70px;
    animation-delay: 0s;
    animation-duration: 1s;
    transition: 0.5s ease;
    outline: none;
}

.logo img {
    width: 100px;
}

.red {
    display: none;
}

.normal {
    display: block;
}

.logo:hover .red {
    display: block;
}

.logo:hover .normal {
    display: none;
}

/* Desktop Navigation Links */

.nav-links {
    display: flex;
    align-items: center;
    justify-content: space-around;
    width: 40%;
    position: relative;
    margin-bottom: 0;
}

.nav-links li {
    list-style: none;
    transition: ease-in 0.5s;
}

.nav-links li:first-child {
    animation-duration: 1s;
    animation-delay: 0.5s;
}

.nav-links li:nth-child(2) {
    animation-duration: 1s;
    animation-delay: 1s;
}

.nav-links li:last-child {
    animation-duration: 1s;
    animation-delay: 1.5s;
}

.nav-links li a {
    text-decoration: none;
    font-family: 'Montserrat', serif;
    font-size: 14px;
    font-weight: bold;
    text-transform: uppercase;
    letter-spacing: 5px;
    color: black;
    user-select: none;
}

.nav-links li a:hover {
    color: rgb(196, 8, 8);
    transition: 0.5s ease;
}

/* Nav Small */

.nav-small {
    display: flex;
    align-items: center;
    justify-content: space-around;
}

/* Nav Icons */

.nav-icons {
    display: flex;
    align-items: center;
    justify-content: space-around;
    width: 70px;
    margin-bottom: 0;
    margin-right: 5vw;
}

.nav-icons li {
    list-style: none;
    transition: ease-in 0.5s;
    cursor: pointer;
}

.nav-icons li:hover {
    color: rgb(196, 8, 8);
}

.nav-icons li:first-child {
    animation-duration: 1s;
    animation-delay: 2s;
}

.nav-icons li:nth-child(2) {
    animation-duration: 1s;
    animation-delay: 2.5s;
}

.nav-icons input {
    position: absolute;
    top: 157.813;
    right: 30;
    opacity: 0;
    transform: translateX(100vw);

    width: 350px;
    padding: 15 20;
    outline: none;
    border: #d3d3d3 solid 1px;
    transition: ease-in 0.1s;
}

.nav-icons input::placeholder {
    font-size: 13;
    letter-spacing: 4px;
    color: #222;
}

#cart-button i sup {
    font-family: 'Montserrat';
    color: white;
    background-color: #222;
    border: 2px solid white;
    border-radius: 100%;
    padding: 2 7;
    font-size: 10px;
    font-weight: lighter;
    margin-left: -7;
    top: -1.3em;
    transition: ease-in 0.5s;
}

#cart-button i:hover > sup {
    background-color: rgb(196, 8, 8);
}

/* Shopping Cart List */

.shop-cart {
    position: absolute;
    top: 157.813;
    right: 30;
    transform: translateX(100vw);

    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    width: 400px;
    max-height: 480px;
    padding: 15 20;
    outline: none;
    border: #d3d3d3 solid 1px;
    background-color: #fff;
    transition: ease-in 0.1s;
}

.cart-list {
    height: fit-content;
    max-height: 1000px;
    overflow-y: scroll;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: flex-start;
}

.cart-list li {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    cursor: default;
    padding-right: 20;
}

.cart-img {
    width: 70px;
    margin-right: 30;
    cursor: pointer;
    user-select: none;
}

.cart-text {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    margin-top: 15;

    font-family: 'Montserrat';
    color: #222;
    letter-spacing: 2px;
}

.cart-text h3 {
    font-size: 16px;
    text-transform: uppercase;
    font-weight: bold;
    color: #222;
    cursor: pointer;
    user-select: none;
}

.cart-text h3:hover {
    color: rgb(196, 8, 8);
}

.cart-text p {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #222;
    cursor: text;
}

.cart-text p span {
    margin: 0 5;
}

.cart-text p span:first-child {
    margin-left: 0;
}

.cart-text .x {
    font-size: 10px;
}

.remove-product {
    margin-left: 30;
    font-size: 18px;
    cursor: pointer;
    color: #222;
}

.remove-product:hover {
    color: rgb(196, 8, 8);
}

.no-product {
    margin-top: 10;
    display: flex;
    align-items: center;
    justify-content: center;
}

.no-product h3 {
    user-select: auto;
}

.no-product h3:hover {
    color: #222;
    cursor: text;
}

.total-price {
    display: flex;
    align-items: center;
    justify-content: center;

    border-top: 1px solid #d3d3d3;
    margin-top: 10;
    padding-top: 20;
    width: 80%;
    text-align: center;
}

.total-price h3 {
    user-select: auto;
}

.total-price h3:hover {
    color: #222;
    cursor: text;
}

.price {
    font-weight: normal;
}

@keyframes slide {
    from {
        opacity: 0;
        transform: translateX(500px);
    }
    to {
        opacity: 1;
        transform: translateX(0);
    }
}

/* Burger Navigation Links */

.burger {
    display: none;
    cursor: pointer;
    animation-delay: 0s;
    animation-duration: 1s;
    width: 50px;
}

.line {
    width: 25px;
    height: 3px ;
    background-color: #222;
    margin: 4px;
    margin-right: 100px;
    transition: ease 0.5s;
}

.burger:hover .line {
    background-color: rgb(196, 8, 8);
}

.burger:hover .line:nth-child(1) {
    margin-left: -5px;
}

.burger:hover .line:nth-child(2) {
    margin-left: 3px;
    width: 30;
}

.burger:hover .line:nth-child(3) {
    width: 20;
    margin-left: -3px;
}

JS:

// Cart Slides in on Button Click

    const cartButton = document.querySelector("#cart-button");

    body.addEventListener("click", () => {

        // On Body Click, Make Shopping Cart Dissapear
        shopCart.style.animation = "";

    });

    cartButton.addEventListener("click", (ev) => {

        // Cart Button Click SLides In Shopping Cart
        if (shopCart.style.animation === "") {
            shopCart.style.animation = "slide 0.3s ease-in forwards";
        } else {
            shopCart.style.animation = "";
        }

        // Remove Search Bar
        searchBar.style.animation = "";

        // Stop Body Clicl From Interrupting
        ev.stopPropagation();
    });

    shopCart.addEventListener("click", (ev) => {
        // Stop Body Clicl From Interrupting
        ev.stopPropagation();
    });  

// Add Items To Cart On Button Click

    (function () {

        // Adding the Product Item
        const cartBtn = document.querySelectorAll(".product-button");
        cartBtn.forEach (function (btn) {
            btn.addEventListener('click', function(event) {

                // Fetch Image 
                let fullPath = event.target.parentElement.previousElementSibling.children[0].src;
                let pos = fullPath.indexOf("Niels") + 5;
                let partPath = fullPath.slice(pos);

                // Fetch Product Name
                let productName = event.target.previousElementSibling.previousElementSibling.textContent;

                // Fetch Product Cost
                let productCost = event.target.previousElementSibling.textContent;
                let finalPrice = productCost.slice(2).trim();

                // Initialize Item Description
                const item = {};
                    item.img = `..${partPath}`;
                    item.name = productName;
                    item.price = finalPrice;

                // Create the List Item
                const cartItem = document.createElement('li');
                cartItem.classList.add('product-cart-item');
                cartItem.innerHTML = `
                    <img src="${item.img}" alt="" class="cart-img">
                    <div class="cart-text">
                        <h3> ${item.name} </h3>
                        <p class="price">$${item.price}</p>
                    </div>
                    <i class="fas fa-times remove-product"></i> 
                `;

                // Insert Product Item Into Cart as a List Item
                const cartList = document.querySelector('.cart-list'); 
                cartList.appendChild(cartItem); 
                alert('Item added to cart.');

                // Remove Product List on Remove Button Click -- !DOES NOT WORK! --
                const removeBtn = document.querySelectorAll('.remove-product')
                removeBtn.forEach (function (rBtn) {
                    rBtn.addEventListener('click', function () {
                        cartItem.remove();
                    });
                }); 

                // Update Total
                showTotals();

            });
        });

        // Showing the Total Price
        function showTotals () {
            const total = [];
            const items = document.querySelectorAll('.price');

            // Fetch Prices As Numbers Into Array
            items.forEach (function (item) {
                itemCartPriceDollar = item.textContent;
                itemCartPrice = itemCartPriceDollar.slice(1); 
                total.push(parseFloat(itemCartPrice));
            }); 

            // Add the Prices
            const totalMoney = total.reduce(function (total, item) {
                  total += item;
                  return total;
              }, 0); 
            const finalMoney = totalMoney.toFixed(2);

            // Display into Total
            document.querySelector('.total-price h3').textContent = `$${finalMoney}`;
            document.querySelector('.item-count').textContent = total.length;
        }

            // Remove "No Products in Cart" Text if there is Products
            let noProduct = document.querySelector('.no-product');
            if (total.length == 0) {
                noProduct.style.display = 'flex';
            } else {
                noProduct.style.display = 'none';
            }
    }) ();

好的,所以使总变量全局化,以便您可以在删除和添加产品案例时更新它。然后传递给 dom 以及显示。您可以在下面看到工作示例。希望对您有所帮助:)

//Ad Items To Cart On Button Click
(function () {
let total = [];
let cartItem;
let finalMoney;
    // Adding the Product Item
    const cartBtn = document.querySelectorAll(".product-button");
    cartBtn.forEach (function (btn) {
        btn.addEventListener('click', function(event) {

            // Fetch Image 
            let fullPath = event.target.parentElement.previousElementSibling.children[0].src;
            let pos = fullPath.indexOf("Niels") + 5;
            let partPath = fullPath.slice(pos);

            // Fetch Product Name
            let productName = event.target.previousElementSibling.previousElementSibling.textContent;
                  
            // Fetch Product Cost
            let productCost = event.target.previousElementSibling.textContent;
            let finalPrice = productCost.slice(2).trim();

            // Initialize Item Description
            const item = {};
                item.img = `..${partPath}`;
                item.name = productName;
                item.price = finalPrice;

            // Create the List Item
            cartItem = document.createElement('li');
            cartItem.classList.add('product-cart-item');
            cartItem.innerHTML = `
                <img src="${item.img}" alt="" class="cart-img">
                <div class="cart-text">
                    <h3> ${item.name} </h3>
                    <p class="price">$${item.price}</p>
                </div>
                <i class="fas fa-times remove-product">remove button</i> 
            `;

            // Insert Product Item Into Cart as a List Item
            const cartList = document.querySelector('.cart-list'); 
            cartList.appendChild(cartItem); 
            alert('Item added to cart.');

            // Remove "No Products in Cart" Text if there is Products
            let noProduct = document.querySelector('.no-product');
            const cartHeight = document.querySelector('.cart-list').offsetHeight;
            if (cartHeight >= 79) {
                noProduct.style.display = 'none';
            } else {
                noProduct.style.display = 'flex';
            }

            // Remove Product List on Remove Button Click -- !DOES NOT WORK! --
            const removeBtn = document.querySelectorAll('.remove-product')
            removeBtn.forEach (function (rBtn) {
                rBtn.addEventListener('click', removeCartItems);
            })
           
            // Update Total
            showTotals();

        });
    });

  function removeCartItems(e){
    let selectedItem = event.target.parentElement;

 finalMoney= (total)?(finalMoney -total.pop()).toFixed(2): 0;
    
    //Display Total Cart Items
    document.querySelector('.item-count').textContent = total.length;
    
    //Display into Total
    document.querySelector('.total-price h3').textContent = `$${finalMoney}`;

    selectedItem.remove();
  }

  // Showing the Total Price
  function showTotals () {
    total = [];
    const items = document.querySelectorAll('.price');

    // Fetch Prices As Numbers Into Array
    items.forEach (function (item) {
      itemCartPriceDollar = item.textContent;
      itemCartPrice = itemCartPriceDollar.slice(1); 
      total.push(parseFloat(itemCartPrice));
    }); 

    // Add the Prices
    const totalMoney = total.reduce(function (total, item) {
      total += item;
      return total;
    }, 0); 
    finalMoney = totalMoney.toFixed(2);

    // Display into Total
    document.querySelector('.total-price h3').textContent = `$${finalMoney}`;
    document.querySelector('.item-count').textContent = total.length;
  }

}) ();
<!DOCTYPE html>

<html>
<head>
    <title>Website Project</title>

    <link href="css/style.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<style>
/* Navigation Bar */


</style>
</head>
<body>
    <!-- Navigation Bar -->
    <nav class="main-nav">

        <!-- Logo -->
        <a href="index.html" class="logo-link">
            <div class="logo animated fadeInLeft">
                <img src="../Media/Logo/logo-red.png" class="red">
                <img src="../Media/Logo/logo.png" class="normal">
            </div>
        </a>

        <!-- Desktop/ Normal Navigation Links -->
        <ul class="nav-links">
            <li class="animated fadeInRight">
                <a href="shop-creator.html">Creator</a>
            </li>
            <li class="animated fadeInRight">
                <a href="shop-men.html">Men</a>
            </li>
            <li class="animated fadeInRight">
                <a href="shop-women.html">Women</a>
            </li>
        </ul>

        <!-- All Smaller Icons Here -->
        <div class="nav-small">

            <!-- Search and Shop Icon-->
            <ul class="nav-icons">

                <!-- Icons -->
                <li class="animated fadeInRight" id="search-button">
                    <i class="fas fa-search"></i>
                </li>
                <li class="animated fadeInRight" id="cart-button">
                    <i class="fas fa-shopping-cart"><sup class="item-count">0</sup></i>
                </li>

                <!-- Search Bar -->
                <input type="text" placeholder="Search">

                <!-- Shopping Cart -->
                <div class="shop-cart">

                    <!-- No Products -->
                    <div class="cart-text no-product">
                        <h3> No products in cart. </h3>
                    </div>

                    <!-- Products -->
                    <ul class="cart-list">
                        <!-- List Items Added By Javascript Here -->
                    </ul>

                    <!-- Total Price -->
                    <div class="cart-text total-price">
                        <h3> [=11=] </h3>
                    </div>

                </div>

            </ul>

            <!-- Mobile/ Burger Navigation Links -->
            <div class="burger animated fadeInRight">
                <div class="line"></div>
                <div class="line"></div>
                <div class="line"></div>
            </div>

        </div>

    </nav>

     <section class="product-container">
        <div class="product-slider">
            <ul id="slide-1">
                <li class="item">
                    <div class="product-item">
                        <div class="product-image">
                            <img src="../Media/Clothes/creator/extendedplay.png" alt="">
                        </div>
                        <div class="product-text">
                            <h1> Extended Play </h1>
                            <h2> 0.69</h2>
                            <span class="product-button">Add to Cart</span>
                        </div>
                    </div>
                </li>
                <li class="item">
                    <div class="product-item">
                        <div class="product-image">
                            <img src="../Media/Clothes/creator/heartache.png" alt="">
                        </div>
                        <div class="product-text">
                            <h1> Heartache </h1>
                            <h2> 9.99</h2>
                            <span class="product-button">Add to Cart</span>
                        </div>
                    </div>
                </li>
                ... 
            </ul>
        </div>
    </section>


</body>
</html>