【问题标题】:Console returns error when I try to change the quantity of shopping cart尝试更改购物车数量时控制台返回错误
【发布时间】:2021-05-28 18:55:04
【问题描述】:

我正在制作一个购物车,我正在使用 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);
  }
}

【问题讨论】:

  • 函数名是“getElementById”而不是“getElementsById”
  • 我已将其更改为元素,但控制台仍然显示 DairyItemsContainer.getElementById 不是函数
  • 必须是document.getElementById
  • 谢谢!当我删除控制台时,控制台现在不会返回错误

标签: javascript html css shopping-cart


【解决方案1】:

使用document.getElementById()。

这将解决错误。

【讨论】:

    猜你喜欢
    • 2021-04-19
    • 2012-04-10
    • 2016-03-27
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多