首页 > 解决方案 > 为什么我的购物车增量计数器不起作用?

问题描述

每次单击“添加到购物车”按钮时,我希望导航栏中的计数增加一个项目,但是当我当前单击“添加到购物车”按钮时,我看不出为什么我的代码不起作用不增加。如果有人能告诉我我缺少什么或给我一个更好的解决方案,我将不胜感激,谢谢!

$('.addCart').on('click', function() {
  console.log(completedIncrements.indexOf(this.id));

  if (completedIncrements.indexOf(this.id) == -1) {
    var count = parseInt($("#count").text());
    $("#count").html(count + 1);

    completedIncrements.push(this.id);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="navbar">
  <a href="shoppingcart.html" class="cart">Shopping Cart (<span id="count">0</span>)</a>
  <a href="shop.html" class="right">Shop</a>
  <a href="contactus.html" class="right">Contact Us</a>
</div>
<a href="shoe1.html"><img id="shoe3" img src="images/shoe1.jpg" alt="shoe1">
<div id="cart1" class="addCart" href="#"><button>Add to cart</button></div>
<a href="shoe2.html"><img id="shoe4" img src="images/shoe2.jpg" alt="shoe2">
<div id="cart2" class="addCart" href="#"><button>Add to cart</button></div>

标签: javascripthtmljquerycart

解决方案


我刚刚检查了你的代码。completeIncrements 在控制台中引发错误并阻止执行您的逻辑。请提供有关该问题的信息,或者使用下面的代码来解决它。

$('.addCart').on('click', function() {

    var count = parseInt($("#count").text());
    $("#count").html(count + 1);

   
})

推荐阅读