【问题标题】:Want to stop a function when a button is clicked in jQuery想要在 jQuery 中单击按钮时停止功能
【发布时间】:2020-11-10 15:25:41
【问题描述】:

我使用 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();
  })
}

【问题讨论】:

  • 问题是,您为什么要自动将任何东西添加到购物篮中?
  • 您可以在用户单击删除按钮时使用会话或本地存储来保存一些标志,并避免在出现标志时添加项目。或者更好地重新考虑你的想法,因为这听起来像是一个糟糕的用户体验;)
  • 与上述 cmets 相呼应:我相信,无论用户在哪个页面上将他们带到您的网站,都已经正确地准备了用户对添加到购物车中的商品的期望。您需要了解如何使用 cookie。假设您使用“ItemAdded”变量,将其保存为 'TRUE' 到 cookie。检查“ItemAdded” cookie 是否存在,如果未找到,请将商品添加到购物车,然后设置 cookie。
  • 你有你的功能的小提琴或演示链接吗?为什么函数总是重复出现。您说的是停止按钮,但添加按钮或删除按钮在哪里。

标签: javascript jquery shopify


【解决方案1】:

我不知道您使用的是什么主题,但这是您可以使用主题执行的操作。我使用了首发主题。

在删除按钮 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 代码。 (根据您的产品更改 Variant 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);

});

【讨论】:

  • 你能告诉我你使用的是什么主题@mh_Pavel?
猜你喜欢
  • 2011-10-30
  • 2016-09-28
  • 1970-01-01
  • 2019-05-12
  • 1970-01-01
  • 2022-01-02
  • 2012-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多