繁体   English   中英

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

[英]Add to cart - avoid page refresh

我有以下设置: 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>

当按下添加到购物车按钮时,页面会刷新。 如何调整它以便在不刷新页面的情况下将产品添加到购物车? 我尝试了其他帖子中建议的一些 jQuery 解决方案,但没有任何运气。 任何的意见都将会有帮助。 谢谢。

您应该在表单上监听提交事件,并且:

  1. 调用event.preventDefault()阻止默认操作(在您的情况下是表单提交)
  2. return false ,最终取消事件

我会做这样的事情


    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;
    });

我也更新了你的小提琴 =>小提琴

暂无
暂无

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

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