想要在jQuery中单击按钮时停止函数



我已经用jQuery为我的Shopify商店编写了一些代码。工作是,当顾客来到我的商店时,他会看到一个产品已经添加到购物车中。

代码运行得很好,但问题是当他单击删除按钮删除该产品时,该产品并没有被删除。它实际上正在删除,但它又被添加到了购物车中。

有什么解决办法吗?我有一个想法,如果有人点击删除按钮,那么该功能将不会再次运行。请告诉我代码应该是什么?

Shopify = Shopify || {};
Shopify.cart = {{ cart | json }};
if (Shopify.cart !=='undefined' && Shopify.cart.items.length === 0) {
jQuery.post('/cart/add.js', {
quantity: 1,
id: 36507787624610,
}).always(function(data){
window.location.reload();
})
}

我不知道你在用什么主题,但这就是你可以用你的主题做什么。我使用了首秀主题。

在删除按钮html 中添加以下数据属性

item-id="{{ item.id }}"

在添加了上面的行之后,在首秀主题中它将是这样的。

<a href="/cart/change?line={{ forloop.index }}&amp;quantity=0" item-id="{{ item.id }}" class="text-link text-link--accent" aria-label="{{ 'cart.label.remove' | t: product: item.title }}" data-cart-remove>{{ 'cart.general.remove' | t }}</a>

在theme.JS文件中添加JS代码。(根据您的产品更改变体ID(

//Adding product in cart
$.getJSON('/cart.js',function( data ) {

$( data.items ).each(function( index, item ) {

//Replace the ID with your variantID
if(item.id == 30329455837287) {
localStorage.setItem("item_removed", "1");
}
});
});


$('a.text-link.text-link--accent').click(function(){
var variant_id = $(this).attr('item-id');

console.log(variant_id);

if(variant_id == 30329455837287){
localStorage.setItem("item_removed", "1");
}

});
setTimeout(function(){
if( localStorage.getItem("item_removed") == "0" || localStorage.getItem("item_removed") == null ) {
$.post('/cart/add.js', {
quantity: 1,
//Replace the ID with your variantID
id: 30329455837287
});
}
}, 500);
});

最新更新