递增、递减、删除和计数 UI 函数 :: 不幸的是不工作

Increment, Decrement, Remove and Count UI Functions :: Unfortunately not Working

请看下面我的 HTML 和 Javascript 代码:

HTML:

<!DOCTYPE html>

<html lang="en">

<head>
    <title>Shopping Cart</title>
    <link rel="stylesheet" href="css/main.css" type="text/css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css"
        integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<body>
    <nav class="top_nav">
        <img src="images/Logo.png" alt="Logo" id="logo" />

        <div id="mySidenav" class="sidenav">
            <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
            <a href="index.html">Home</a>
            <a href="AboutUs.html">About Us</a>
            <a href="Catalogue.html">Catalogue</a>
            <a href="ContactUs.html">Contact Us</a>
        </div>
        <span id="hamburger" onclick="openNav()">&#9776;</span>

        <div id="search_bar">
            <input type="search" placeholder="search..." />
            <button><i class="fas fa-search"></i></button>
        </div>
        <!-- Created a shopping cart button that shows how many items are in the basket. -->
        <div>
            <a href="ShoppingCart.html" class="button" id="cart-button">
                <i class="fas fa-shopping-cart" id="cart"></i>
                <span class="amount-products badge badge-warning carttotal" id="lblCartCount" onchange="countCart()">0</span>
            </a>
        </div>
    </nav>
    <!-- Created a <div> so that the page can be populated by dynamically created elements. -->
    <div id="populatecart">
        <h1>Shopping Cart</h1>
    </div>

    <footer>
        <p> &copy; Hyperion Development.&nbsp;&nbsp; All Rights Reserved.&nbsp;&nbsp; Proudly created by <a
                href="http://www.hyperiondev.com">Hyperion Development</a></p>
    </footer>

    <script type="text/javascript" src="js/main.js"></script>
</body>

</html>

Javascript:

// Navigation bar ***
// Function to display the side navigation area.
function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
}
// Function to close the side navigation area.
function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
}

// Shopping cart ***
// Created a map array for items to be displayed in cart.
let cart = []
// Function to stringify and set items in local storage.
function saveCart() {
    localStorage.setItem("cart",
        JSON.stringify(cart)
    )
}
// Function to parse and get items from local storage.
function loadCart() {
    cart = JSON.parse(localStorage.getItem("cart"))
    if (cart === null) {
        cart = []
    }
}
// Called loadCart function.
loadCart()
// Created a constructor function to add items to the cart.
class Plant {
    constructor(name, image, price) {
        this.name = name
        this.image = image
        this.price = price
        this.count = 1
    }
}
// Created the new products and included the names, images and prices.
let plant1 = new Plant(
    "Agapanthus (Purple Cloud/ African Lily)",
    "images/Agapanthus.jpg",
    95,
);
let plant2 = new Plant(
    "Sweet Alyssum (Royal Carpet)",
    "images/Alyssum.jpg",
    25,
);
let plant3 = new Plant(
    "Clivia (Natal Lily/ Bush Lily)",
    "images/Clivia.jpg",
    95,
);
let plant4 = new Plant(
    "Dianthus (Ideal Select Violet)",
    "images/Dianthus.jpg",
    45,
);
let plant5 = new Plant(
    "Dahlia (Dreamy Eyes)",
    "images/Dahlia.jpg",
    40,
);
let plant6 = new Plant(
    "African Daisy (Bright Lights Yellow)",
    "images/Daisy.jpg",
    50,
);
let plant7 = new Plant(
    "Marigold (Honeycomb)",
    "images/Marigold.jpg",
    35,
);
let plant8 = new Plant(
    "Petunia (Supercal Neon Rose)",
    "images/Petunia.jpg",
    45,
);
// Created products array.
let myPlants = [plant1, plant2, plant3, plant4, plant5, plant6, plant7, plant8];
// Function to add and increase items in the cart.
function addCart(name, image, price) {
    // Looping through products in order to add or increase products.
    for (let i = 0; i < cart.length; i++) {
        if (cart[i].name === name) {
            cart[i].count += 1
            saveCart()
            return
        }
    }
    let plant = new Plant(name, image, price)
    cart.push(plant)
    saveCart()
}
// Function to remove and decrease items in the cart.
function removePlant(name, count = 1) {
    // Looping through products in order to remove or decrease products.
    for (let i = 0; i < cart.length; i++) {
        let plant = cart[i];
        if (plant.name === name) {
            if (plant.count > count) {
                plant.count -= count
            } else {
                cart.splice([i], 1)
            }
            break
        }
    }
    saveCart()
}
// Function to calculate discount total once a discount code is entered.
function calculateDiscount(discountCode) {
    if (discountCode === 'petals') {
        return 0.90;
    } else if (discountCode === 'flowers') {
        return 0.75;
    } else if (discountCode === 'fields') {
        return 0.5;
    } else {
        return 0;
    }
}
// Function to work out the total costs of the items
function totalCart() {
    let total = 0
    for (const plant of cart) {
        total +=
            plant.count * plant.price
    }
    return total;
}
// Created function to store the amount of items in the navigation bar locally underneath the cart icon. 
 function countCart() {
     let count = 0
     for (const plant of cart) {
         count += plant.count
     }
     return count;
 }

function countCart() {
    let productNumbers = document.getElementById('cartquantity');
    if (productNumbers) {
        document.querySelectorAll(".carttotal").textContent = productNumbers;
    }
    saveCart()
}

// Function using the data attributes assigned in the product html pages to be able to add items by clicking the add-to-cart button.
function addVisualCart(plant) {
    let name = plant.getAttribute("data-name");
    let image = plant.getAttribute("data-image");
    let price = plant.getAttribute("data-price");
    addCart(name, image, price)
    alert(`${name} was successfully added to the cart. Your total is now R${totalCart()}.00`)
}

let quantity = 0;

document.getElementById('cartquantity').innerHTML = quantity;

function increaseCount() {
  document.getElementById('cartquantity').innerHTML = ++quantity;
}

function decreaseCount() {
  document.getElementById('cartquantity').innerHTML = --quantity;
}

let btns = document.querySelectorAll('.remove');
btns.forEach(function(btn) {
  btn.addEventListener('click', updateAmount);
});

function updateAmount() {
  var num = parseInt(document.getElementById('cartquantity').textContent.trim(), 10);
  this.value === "delete" ? num-- : num++;
  document.getElementById('.cartquantity').textContent = num;
}

// Function to generate a random order reference number when clicking on the "Confirm Order" button.
function submitOrder() {
    let orderRef = Math.random().toFixed(36).substr(2, 9);
    alert(`Thank you for your order. Your order reference number is ${orderRef}`);
}
// Function to display the cart items via the <div> "populatecart" that was created in the shopping cart's HTML page.
function displayCart() {
    let productContainer = document.getElementById("populatecart");
    let total = totalCart()
    if (addCart && productContainer) {
        Object.values(cart).map(item => {
            // Dynamically adding the items and elements to the HTML using the productContainer.
            productContainer.innerHTML += `
        <table class="products">
            <tr>
                <th class="cartimage productheader"></th>
                <th class="product-name productheader">PRODUCT</th>
                <th class="price productheader">PRICE</th>
                <th class="quantity productheader">QUANTITY</th>
                <th class="total productheader">TOTAL</th>
                <th class="remove productheader"></th>
            </tr>
            <tr>
                <td class="productlist"><img src=${item.image} class="cartimage" alt="cartimage"></td>
                <td class="product-name productlist">${item.name}</td>
                <td class="price productlist">R${item.price}</td>
                <td class="quantity productlist">
                    <button id="increasecount" class="add" onclick="increaseCount()><i class="fas fa-caret-square-up"></i></button>
                    <p id="cartquantity" class="productcount productlist">${item.count}</p>
                    <button id="decreasecount" class="delete" onclick="decreaseCount()"><i class="fas fa-caret-square-down"></i></button>
                </td>
                <td class="total productlist">R${item.price * item.count},00</td>
                <td class="productlist"><button class="remove" value="delete" onclick="removePlant()"><i class="fas fa-trash-alt"></i> Remove</button></td>
            </tr>
        </table>`
        });
        // Dynamically adding the vat and other totals and select elements to the HTML using the productContainer.
        productContainer.innerHTML += `
        <form id="formcontainer"> 
        <div class="discount">
            <label id="discountlabel">Do you have a discount code?</label>
            <input id="discountinput" placeholder=" --- Enter code here ---"/>
            <button id="discountbutton" onclick="discountTotal()">Submit</button>
        </div>
        <label id="dropdownlabel">Is this for yourself or a gift for someone else's garden?:</label>
        <select id="dropdown">
        </select> 
        <div id="collectordelivery">
            <label>How would you like to receive your order?</label><br />
            <input type="radio" name="getitmethod" id="collection" value="collection" onclick="deliveryOrCollection()"/>Collection (Free of charge)<br />
            <input type="radio" name="getitmethod" id="delivery" value="delivery" onclick="deliveryOrCollection()"/>Delivery
        </div>
        <div id="deliveryoptions">
            <label>Select the preferred delivery option:</label><br />
            <input id="EcoD" value="15.00" type="radio" class="deliveryinput"/> Economy Delivery (5-7 working days) at R15.00<br />
            <input id="StdD" value="25.00" type="radio" class="deliveryinput"/> Standard Delivery (2-4 working days) at R25.00<br />
            <input id="ExpD" value="50.00" type="radio" class="deliveryinput"/> Expedited Delivery (1-2 working days) at R50.00
        </div>
        </form>
        <div id="vattotalcontainer"> 
            <h4 id="vattotaltitle">VAT:</h4>
            <h4 id="vattotal">R${total * 0.15}</h4>
        </div>
        <div id="baskettotalcontainer">
            <h4 id="baskettotaltitle">Total:</h4>
            <h4 id="baskettotal">R${total},00</h4>
        </div>
        <button id="submitorder" onclick="submitOrder()">Confirm Order</button>`
    }
}
// Function to calculate the discount total and to dedust this from the order total.
function discountTotal() {
    let discountCode = document.getElementById("discountinput").value;
    let total = document.getElementById("baskettotal");
    total.innerHTML = "R" + totalCart() * calculateDiscount(discountCode);
}

displayCart();


// jQuery ***
$(document).ready(function () {

    $('.quantity').each(function() {
        var $this = $(this);
        var $input = $this.find('.productcount');
        $this.on('click', '.add', function() {
          var val = parseInt($input.val());
          $input.val(++val);
        }).on('click', '.delete', function() {
          var val = parseInt($input.val());
          $input.val(--val);
        });
      });
// Created the dropdown options via jQuery with this function
    let myOptions = {
        select : '--- Please select ---',
        forme : 'This is for me.',
        gift : 'This is a gift. Please do not include a slip.'
    };
    let mySelect = $('#dropdown');
    $.each(myOptions, function(val, text) {
        mySelect.append(
            $('<option></option>').val(val).html(text)
        );
    });

    // Created function to hide and show the delivery functions when someone selects either collect or delivery.
    $("#deliveryoptions").hide();
    $('input[name="getitmethod"]').click(function () {
        $("#deliveryoptions").hide();
        if ($('input[name="getitmethod"]').is(':checked')) {
            let radioValue = $("input[name='getitmethod']:checked").val();
            if (radioValue === "delivery") {
                $("#deliveryoptions").show();
            } else {
                $("#deliveryoptions").hide();
            }
        }
    });
});

//Created a function for the bee to "fly on the "Catalogue page".
$(document).keydown(function (key) {
    switch (parseInt(key.which, 10)) {
        // Left arrow pressed.
        case 37:
            $('.buzzerbee').stop().animate({
                left: "-=200px"
            }, 'fast');
            break;
            // Up arrow pressed.
        case 38:
            $('.buzzerbee').stop().animate({
                top: '-=200px'
            }, 'fast');
            break;
            // Right arrow pressed.
        case 39:
            $('.buzzerbee').stop().animate({
                left: '+=200px'
            }, 'fast');
            break;
            // Down arrow pressed.
        case 40:
            $('.buzzerbee').stop().animate({
                top: '+=200px'
            }, 'fast');
            break;
    }
})

// Created function to hide or show the product summary table on the "Catalogue" page.
$("#hide").click(function () {
    $("table").hide(1000);
});
$("#show").click(function () {
    $("table").show(1000);
});

// Created a chained function for the view our catalogue header on the "About Us" page.
$("#seeheaderbetter").click(function () {
    $("#viewcatalogue").css("color", "#05520f").animate({
            width: "100%"
        })
        //Enlarges the font size and makes the element bigger.
        .animate({
            fontSize: "46px"
        })
        .animate({
            borderWidth: 30
        });
});

我正在尝试执行递增、递减和删除功能,但不幸的是没有任何成功。我被告知增量和减量函数可以通过调用 addCart 和 removePlant 函数来操作,因为它们本质上做同样的事情。

应通过单击相应的按钮来执行这些功能。我已尝试将 eventListeners 添加到 Javascript 并通过在 HTML 元素中引用 onclick,但没有任何反应。当我在 console.log 中测试 addCart 和 removePlant 时,它运行良好。它只是在 UI.

中进行操作

我也无法通过导航栏上的 countCart 函数填充购物车的徽章计数器。我已经尝试过与上面相同的方法(eventListeners 和 HTML onclick),因为它也应该由一个按钮来操作,但不幸的是它没有显示。

如果有人能指出我实现这些功能的正确方向,我将不胜感激。

我设法解决了上述问题,感谢 Abronsius 教授指出这将是一个字符串。

我的解决方案如下:

Javascript:

// Function using the data attributes assigned in the product html pages to be able to delete items by clicking the remove button.
function removeVisualCart(plant) {
  let name = plant.getAttribute("data-name");
  let count = plant.getAttribute("data-count");
  removePlant(name, count);
  countInCart();

  location.reload();
  alert(`${name} was successfully removed`);
}

// Created an increment function to amend the item count in the cart by clicking on the "up" arrow.
function increment(plant) {
  let name = plant.getAttribute("data-name");
  let image = plant.getAttribute("data-image");
  let price = plant.getAttribute("data-price");
  addCart(name, image, price);
  countInCart();

  location.reload();
}

// Created an decrement function to amend the item count in the cart by clicking on the "down" arrow.
function decrement(plant) {
  let name = plant.getAttribute("data-name");
  removePlant(name, 1);
  countInCart();

  location.reload();
}

// Created function to show the amount of items in the navigation bar on the cart icon.
function countInCart() {
  let productNumbers = document.getElementById("lblCartCount");
  if (productNumbers) {
    productNumbers.innerHTML = countCart();
  }
}
countInCart();

HTML:

<div>
            <a href="ShoppingCart.html" class="button" id="cart-button">
                <i class="fas fa-shopping-cart" id="cart"></i>
                <span class="amount-products badge badge-warning carttotal" id="lblCartCount" onchange="countCart()">0</span>
            </a>
        </div>

<td class="quantity productlist">
                    <button 
                    id="increasecount" 
                    class="add" 
                    data-name="${item.name}"
                    data-image="${item.image}"
                    data-price="${item.price}"
                    onclick="increment(this)"
                    >
                    <i class="fas fa-caret-square-up"></i>
                    </button>
                    <p id="cartquantity" class="productcount productlist">${item.count}</p>
                    <button 
                    id="decreasecount" 
                    class="delete" 
                    data-name="${item.name}"
                    onclick="decrement(this)"  
                    ><i class="fas fa-caret-square-down"></i></button>
                </td>
                <td class="total productlist">R${
                  item.price * item.count
                },00</td>
                <td class="productlist">
                <button 
                data-name="${item.name}"
                data-count="${item.count}"
                onclick="removeVisualCart(this)"
                class="remove" value="delete" onclick="removePlant()">
                    <i class="fas fa-trash-alt">
                    </i> Remove</button></td>
            </tr>
        </table>

希望对遇到同样问题的其他人有所帮助。