почему моя корзина не обновляет итоговую сумму правильно - PullRequest
0 голосов
/ 01 мая 2020

моя корзина работает (итоговая сумма) до тех пор, пока я не удалю элемент, затем итоговая сумма читает последнюю сумму перед тем, как я удалил элемент, определенно где-то была орфографическая ошибка, но я смотрю на нее в течение 3 дней, теперь какая-нибудь помощь? сообщение об ошибке: cart. js: 154 Uncaught TypeError: Невозможно прочитать свойство 'innerText' из undefined в updateCartTotal (cart. js: 154) в HTMLButtonElement.removeCartItem (cart. js: 52) для школьного проекта Завтра я следил за упрощенным веб-разработчиком, но я явно заблудился в пути где-то

if(document.readyState == "loading")
    {
        document.addEventListener("DOMContentLoaded", ready)
    } 
    else
    {
        ready()
    }




function ready ()   
{
    //get the btn-danger class as a variable
    var removeCartItemButtons = document.getElementsByClassName("btn-danger")
        //loop through the buttons waiting for them to be clicked and then perform the function to remove them from the cart
        for (var i = 0; i < removeCartItemButtons.length; i++)
            {
                var button = removeCartItemButtons[i]
                button.addEventListener("click", removeCartItem)
            }

        //fix quantity updating the total and stopping negative cart quantities
        var quantityInputs = document.getElementsByClassName("cart-quantity-input")
        //loop throught the quantities listening for when the input changes its value
        for (var i = 0; i < quantityInputs.length; i++)
            {
                //input = whatever iteration we are on
                var input = quantityInputs[i]
                //listen for a change and execute function "quantityChanged"
                input.addEventListener("change", quantityChanged)
            }

        //creating the javascript for all add to cart buttons on the site 
        var addToCartButtons = document.getElementsByClassName("shop-item-button")
        //constantly looping throught the buttons waiting for an event
        for (var i = 0; i < addToCartButtons.length; i++)
            {
                //whatever button is clicked executes the function
                var button = addToCartButtons[i]
                button.addEventListener("click", addToCartClicked)
            }
}   

function removeCartItem(event)
{
    //on the function event the target of the event is to remove boththe element its inside and also the element that that element is inside... the double parentElement
    var buttonClicked = event.target
    buttonClicked.parentElement.parentElement.remove()
    //call the function that updates the total price
    updateCartTotal ()
}

    //this function is what we want to do when the quantity value is changed 
    function quantityChanged(event)
    {
        //get the quantity in the input
        var input = event.target
        //check if theres a number in the input and that it is at least 1 
        if (isNaN(input.value) || input.value <= 0)
            {
                input.value = 1
            }
        //once we no theres is a valid number entered, call the function to update the cart again
        updateCartTotal()
    }





//the function executed when add to cart buttons are clicked
function addToCartClicked(event)
    {
        //initialises the button as the event target
        var button = event.target
        //getting the parent div the button is in
        var shopItem = button.parentElement
        //getting the div where the details of the product is
        var title = shopItem.getElementsByClassName("details")[0].innerText
        //the price of the product
        var price = shopItem.getElementsByClassName("price")[0].innerText
        //and the src of the product
        var imageSrc = shopItem.getElementsByClassName("shop-item-image")[0].src
        console.log(title,price, imageSrc)
        addItemToCart(title, price, imageSrc)   
        updateCartTotal()
    }   

        //creating a new method for adding all this into the cart keeping the title price and imageSource variables with the function
function addItemToCart(title, price, imageSrc)
    {
        //creating an empty div
        var cartRow = document.createElement("div")
        cartRow.classList.add("cart-row")
        //adding the newly created cart row to the cart items
        var cartItems = document.getElementsByClassName("cart-items")[0]
        //stop duplicate items in the cart
        //get the names of all the items
        var cartItemNames = cartItems.getElementsByClassName("cart-item-title")
        //loop through the names
        for (var i = 0; i < cartItemNames.length; i++)
            {
                //check if the names in the cart equal to the title I am adding
                if(cartItemNames[i].innerText == title)
                    {
                        //alert that the item is already in the cart
                        alert("this item is already in your cart")
                        return
                    }
            }
        //show what to put into the rows and replace the image, title and price on each new item
        var cartRowContents = `
            <div class="cart-row">

                <div class="cart-item cart-column">
                <img class="cart-item-image"src="${imageSrc}" width="100" height="100">
                <span class="cart-item-title">${title}</span>
                </div>

                <span class="cart-price cart-column">${price}</span>

                <div class="cart-quantity cart-column">
                <input class="cart-quantity-input" type="number" value="1">
                <button class="btn btn-danger">Remove</button>

            </div>`
        cartRow.innerHTML = cartRowContents
        //add the items onto the cart
        cartItems.append(cartRow)
        //event listener for the remove button
        cartRow.getElementsByClassName("btn-danger")[0].addEventListener("click", removeCartItem)
        //event listener for quantity changed
        cartRow.getElementsByClassName("cart-quantity-input")[0].addEventListener("change", quantityChanged)
    }


    function updateCartTotal ()
    {
        //get the first cart items element
        var cartItemContainer = document.getElementsByClassName("cart-items")[0]
        //get the cart rows but only from the cart items
        var cartRows = cartItemContainer.getElementsByClassName("cart-row")
        //initialise the total
        var total = 0
        //loop through the cart rows for price and quantity
        for (var i = 0; i < cartRows.length; i++)
        {
            var cartRow = cartRows[i]
            //get the first pricee
            var priceElement = cartRow.getElementsByClassName("cart-price")[0]
            //get the quantity
            var quantityElement = cartRow.getElementsByClassName("cart-quantity-input")[0]
            //Get the information from inside the element not just the element itself, replace the euro sign with nothing and make it a Number
            var price = parseFloat(priceElement.innerText.replace("€", ""))
            //get the quantity and multiply it by the price for the running total
            var quantity = quantityElement.value
            total = total + (price * quantity)
        }
        //multiplying the totoal by 100 and divinding by 100 again will round the total to stop any .999999999998's showing up
        total = Math.round(total * 100) / 100
        //update the total price add the euro sign back in
        document.getElementsByClassName("cart-total-price")[0].innerText = "€" + total
    }   

спасибо всем, кто может мне помочь

1 Ответ

0 голосов
/ 01 мая 2020

PriceElement равен нулю. Похоже, что в этом элементе cart-row нет элементов с классом cart-price.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...