在我的updateCartTotal()函数中,我想要console.log从我的购物车中删除的元素。
每次按下删除按钮时,我都希望它打印出item, 和price。但是,每当我这样做时,它都会返回未定义。在某些情况下,它只能识别 1 个项目。我不认为我的 JavaScript 代码有问题,而可能是我的 HTML
const updateCartTotal = () => {
var cartItemContainer = document.getElementsByClassName('cart-items')[0]
var cartRows = cartItemContainer.getElementsByClassName('cart-row')
for(var i = 0; i < cartRows.length; i++){
var cartRow = cartRows[i];
var itemElement= cartRow.getElementsByClassName('cart-item')[0].innerHTML
var priceElement = cartRow.getElementsByClassName('cart-price')[0].innerHTML
var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
var item = itemElement.innerText
var price = priceElement.innerText
// var quantity = quantityElement.value
console.log(item, price)
}
}
<section class="container shopping-cart">
<div class="title">Cart</div>
<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="cart-items">
<div class="cart-row">
<div class="cart-item">
<span class="cart-item-title">Item 1</span>
</div>
<span class="cart-price ">$14.99</span>
<div class="cart-quantity-input">
<input type="number" value="1">
<button class="btn btn-danger ml-5" type="button">REMOVE</button>
</div>
</div>
<div class="cart-row">
<div class="cart-item">
<span class="cart-item-title ">Item 2</span>
</div>
<span class="cart-price">$79.99</span>
<div class="cart-quantity-input">
<input type="number" value="2">
<button class="btn btn-danger ml-5" type="button">REMOVE</button>
</div>
</div>
</div>
</section>
相关分类