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



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

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

最新更新