简体   繁体   English

添加到购物车 - 避免页面刷新

[英]Add to cart - avoid page refresh

I have the following setup: https://jsfiddle.net/uosLke60/我有以下设置: https ://jsfiddle.net/uosLke60/

 input.Add_To_Cart_Button { background-color: #000; color: #fff; border: none; font: inherit; cursor: pointer; font-size: 13px; margin-bottom: 40px; width: 120px; -webkit-appearance: none; border-radius: 0; }
 <div class="Product_Card_Button"> <form method="post" action="/cart/add"> <quantity-input class="quantity" style="width: 120px; min-height: 25.4px; display: inline-flex;"> <button class="quantity__button no-js-hidden" name="minus" type="button"> - </button> <input class="quantity__input" type="number" name="quantity" id="quantity" min="1" value="1" style="text-align: center;"> <button class="quantity__button no-js-hidden" name="plus" type="button">+</button> </quantity-input> <br> <input type="submit" value="Add to cart" class="Add_To_Cart_Button" /> </form> </div>

When the add to cart button is pressed, the page refreshes.当按下添加到购物车按钮时,页面会刷新。 How can I adjust it so that the product is added to cart without the page refresh?如何调整它以便在不刷新页面的情况下将产品添加到购物车? I have tried a number of jQuery solutions suggested in other posts but without any luck.我尝试了其他帖子中建议的一些 jQuery 解决方案,但没有任何运气。 Any suggestions would be helpful.任何的意见都将会有帮助。 Thanks.谢谢。

You should listen for the submit event on your form and:您应该在表单上监听提交事件,并且:

  1. call event.preventDefault() which blocks the default action (in your case the form submit)调用event.preventDefault()阻止默认操作(在您的情况下是表单提交)
  2. return false , which ultimately cancels the event return false ,最终取消事件

I would do something like this我会做这样的事情


    function handleAddToCart(form) {
        const url = form.getAttribute("action");
      const formData = new FormData(form);
      doSomePost(url, formData);
    }
    
    // Cache this if possible
    document.querySelector("[add-to-cart-form]")
    .addEventListener("submit", (e) => {
        e.preventDefault();
      handleAddToCart(e.target);  
      return false;
    });

I updated your fiddle as well => fiddle我也更新了你的小提琴 =>小提琴

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

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