带有JavaScript的购物车

时间:2019-03-23 22:41:13

标签: javascript

我正在使用Vanilla JavaScript构建购物车,并且正在尝试使用Console.Log,以在单击按钮以删除产品时显示产品“ $ 19.99”的价格,但在Console.Log和i中没有显示任何内容认为问题出在html上,但我找不到它,有什么主意吗?

<div class="click-cart">
    <div class="cart-row">
        <span class="cart-item cart-header cart-column">ITEM</span>
        <span class="cart-price cart-header cart-column">PRICE</span>
        <span class="cart-quantity cart-header cart-column">QUANTITY</span></div>
      <div class="olp">
        <div class="lakn">
        <img class="shop-item-cart" src="https://cdn.thewirecutter.com/wp-content/uploads/2018/04/canon-dslrs-march-2018-2x1-lowres3496.jpg">
        <span class="shop-title">Album 1</span>
        <span class="shop-price">$19.99</span>
        <input class="quantity-input" type="number" value="1">
        <button class="delete-cart">X</button>
      </div></div>
        <div class="clear-checkout">
      <button class="checkout">Checkout</button>
      <button class="clear-cart">Clear Cart</button></div>
    <div class="cart-items">
      </div>
      <div class="cart-total">
          <strong class="cart-total-title">Total</strong>
          <span class="cart-total-price">$10.79</span>
      </div>

    for (let i = 0; i < removeCartItemButtons.length; i++) {
    let button = removeCartItemButtons[i]
    button.addEventListener('click', function (event) {
    let buttonCliked = event.target
    buttonCliked.parentElement.parentElement.remove()
    updateCartTotal ()
    })
}

function updateCartTotal () {
    let cartItemContainer = document.querySelector('.click-cart');
    let cartRows = cartItemContainer.querySelector('.cart-row');
    for (let i = 0; i < cartRows.length; i++) {
        let cartRow = cartRows[i]
        let priceElement = cartRow.querySelector('.shop-price');
        let quantityElement = cartRow.querySelector('.quantity-input');
        let price = priceElement.innerText
        console.log(price)
    }
}```

1 个答案:

答案 0 :(得分:0)

<div class="cart-row">
    <span class="cart-item cart-header cart-column">ITEM</span>
    <span class="cart-price cart-header cart-column">PRICE</span>
    <span class="cart-quantity cart-header cart-column">QUANTITY</span>
</div>

shop-price元素不在cart-row div中。

此外,您的for循环不会运行,因为cartRows不是数组,而是单个HTMLElement,长度为undefined,请使用cartItemContainer.querySelectorAll('.cart-row')来获取一个可交互的NodeList

此外,由于在使用updateCartTotal函数之前已删除了该元素,因此必须将价格变量预设为0。

function updateCartTotal () {
let cartItemContainer = document.querySelector('.click-cart');
let cartRows = cartItemContainer.querySelectorAll('.cart-row');
let price = 0;
for (let i = 0; i < cartRows.length; i++) {
    let cartRow = cartRows[i]
    let priceElement = cartRow.querySelector('.shop-price');
    let quantityElement = cartRow.querySelector('.quantity-input');
    if (priceElement) {
      price += Number(priceElement.innerText.replace('$',''));
    }
    console.log(price);
}
}