[英]Console returns error when I try to change the quantity of shopping cart
我正在制作一個購物車,我正在使用 javascript 作為刪除和數量按鈕。 我不明白我的代碼哪里出錯了。 該教程說我的控制台在我登錄時應該返回變量 priceElement 和 quantityElement 。 但是,當我這樣做時,我的控制台沒有任何顯示。 此外,當我從購物車中移除商品時,控制台會顯示“dairyItemsContainer.getElementById 不是函數”。 當有人刪除一個項目時,我希望能夠使總數、價格和刪除按鈕同步,以便更新總數。 任何人都可以幫忙嗎?
這是購物車的 html:
<div>
<table>
<thead>
<tr>
<th>Items</th>
<th>Price</th>
<th>Quantity</th>
<th></th> <!--- remove --->
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>Brown Sugar</td>
<td id='price'>€1.59</td>
<td class='quantity'><input class="quantity" name="quantity[]" type="text" value="2"></td>
<td><button type="button" name="button" id='buttonCart' class='buttonRemoved'>Remove</button></td>
</tr>
<tr>
<td>Soda Bread</td>
<td id='price'>€2.99</td>
<td class='quantity'><input class="quantity" name="quantity[]" type="text" value="1"></td>
<td><button type="button" name="button" id='buttonCart' class='buttonRemoved'>Remove</button></td>
</tr>
<tr>
<td>Milk</td>
<td id='price'>€0.99</td>
<td class='quantity'><input class="quantity" name="quantity[]" type="text" value="2"></td>
<td style='float: left;'><button type="button" name="button" id='buttonCart' class='buttonRemoved'>Remove</button></td>
</tr>
<tr>
<td></td>
<td></td>
<td class='totalFont'>Total</td>
<td class='total'>€5.57</td>
</tr>
</tbody>
</table>
這是 JavaScript 代碼:
var removeCartItems = document.getElementsByClassName("buttonRemoved");
console.log(removeCartItems);
for (var i = 0; i < removeCartItems.length; i++) {
var button = removeCartItems[i];
button.addEventListener("click", function (event) {
var buttonClicked = event.target;
buttonClicked.parentElement.parentElement.remove();
updateTotal();
});
}
function updateTotal() {
var dairyItemsContainer = document.getElementsByClassName("dairyItems")[0];
var cartRows = dairyItemsContainer.getElementById("dairyTotalHelp");
for (var i = 0; i < cartRows.length; i++) {
var cartRows = cartRows[i];
var priceElement = cartRows.getElementsByClassName("price")[0];
var quantityElement = cartRows.getElementsByClassName("quantity")[0];
console.log(priceElement, quantityElement);
}
}
使用document.getElementById()
。
這將解決錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.