简体   繁体   English

点击事件不会在首次点击时触发,而是在每次点击后触发

[英]Click event doesn't fire on first click but does everytime after

I am making my add to cart button update a span counter of items in the cart which works every time after you click the button once but does not work on the first click 我正在将“添加到购物车”按钮更新为购物车中的商品的跨度计数器,每次单击该按钮后,该计数器每次都有效,但第一次单击时不起作用

I have tried using .on method which gives the same outcome and have tried using document.ready which also doesn't effect it. 我尝试使用.on方法给出相同的结果,并尝试使用document.ready也不起作用。

$(document).ready(function() {
  $('#addToCart').on('click', function() {
    jQuery.getJSON('/cart.js', function(cart) {
      $("span.count").html(cart.item_count);
    });
  }); 
});

I expect the addToCart button to update the span.count on every click. 我希望addToCart按钮可以在每次点击时更新span.count。 The actual result is that it works after the first click. 实际结果是它在第一次单击后就可以使用。

$(document).ready(function() { 
  $('#addToCart').on('click', function() { 
    alert("Hello"); 
  }); 
});

Please try it now Hope this ll helpful for you 请立即尝试,希望对您有所帮助

Button clicked every time, there is no issue with button click 每次单击按钮,按钮单击就没有问题

 $(document).ready(function() { $('#addToCart').on('click', function() { alert('button clicked'); jQuery.getJSON('/cart.js', function(cart) { $("span.count").html(cart.item_count); }); }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/shopify-cartjs/0.4.1/cart.min.js"></script> <button id="addToCart" type="button">Add to cart</button> <span>Cart Items: </span> <span class="count">0</span> 

You can try the solution provided below if it works: 如果可行,您可以尝试以下提供的解决方案:

$(document).ready(function() {
    $(document).on('click', '#addToCart', function() {  
        alert('button clicked');
        jQuery.getJSON('/cart.js', function(cart) { 
            $("span.count").html(cart.item_count);
        });
    }); 
});

I want to suggest you another way to update cart without using Ajaxify cart API. 我想建议您另一种无需使用Ajaxify购物车API即可更新购物车的方法。 You should try once. 您应该尝试一次。 I'm talking about cart.js 我说的是cart.js

You just need to include below CDN in your theme header. 您只需要在主题标题中的CDN下方添加即可。

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/shopify-cartjs/0.4.1/cart.min.js"></script>

After that you need to add tag "data-cart-render" in your html. 之后,您需要在html中添加标签“ data-cart-render”。 It will automatically render cart item count inside the html tag. 它将自动在html标签中呈现购物车项目计数。 Example: 例:

<span data-cart-render="item_count"></span>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM