【问题标题】:Woocommerce - added_to_cart triggerWoocommerce - added_to_cart 触发器
【发布时间】:2016-03-23 22:24:33
【问题描述】:

我正在尝试使用 WooCommerce added_to_cart 触发器在将特定产品添加到购物车时触发弹出窗口。到目前为止,我已经成功实现了以下目标:

jQuery('body').on('added_to_cart',function() {
        alert("testing!");
    });

当任何产品添加到购物车时,这会显示一个警告框。但是,我希望警报只显示特定类别。但是如何查看添加到购物车的产品属于哪个类别?

添加到购物车的来源在这里: https://github.com/woothemes/woocommerce/blob/master/assets/js/frontend/add-to-cart.js

还有这个问题的触发器:

$( document.body ).trigger( 'added_to_cart', [ fragments, cart_hash, $thisbutton ] );

【问题讨论】:

    标签: php jquery ajax wordpress woocommerce


    【解决方案1】:

    假设您使用的是默认的 WooCommerce html 结构,这应该对您有用。

    我已通过 Storefront 演示页面上的 Chrome 控制台运行它对其进行了测试,可在此处找到:http://demo2.woothemes.com/storefront/shop/。仅当将“收音机”产品添加到购物篮时,它才会显示警报消息,它会从该产品的父 <li> 上的类中找到类别。

    $ = jQuery;
    var lastCategory;
    
    $('body').on('added_to_cart',function() {
        if(lastCategory === 'radios'){
            alert('a radio was added!');
        }
    });
    
    $('.add_to_cart_button').on('click',function() {
        lastCategory = $(this).closest('li').attr('class').split('product-cat-')[1].split(' ')[0];
    });
    

    【讨论】:

    • 不幸的是,我无法让它工作 :-( 我不能以某种方式从 added_to_cart 中得到它吗?
    • 您是否尝试过在 Storefront 演示中通过控制台运行上述代码?然后再为您的网页?它对两者都不起作用,还是仅对您起作用?到页面的链接会很方便,所以我可以看到 HTML。
    • 我无法让它在我自己的网站上运行。但是,您的建议使我朝正确的方向点头,最终我为所需的产品提供了一个名为 popup 的数据属性,当它们应该制作一个警报框时。现在下面的代码有点工作:var popup; jQuery('.add_to_cart_button').click(function() { popup = jQuery(this).attr('popup'); }); jQuery('body').on('added_to_cart',function() { if (popup === 'yes') { alert(popup); } }); 唯一的问题是我收到 3 或 4 个警报。我怎样才能强制它只触发一次?这是我的网站:tiny.cc/w65c7x
    【解决方案2】:

    所以我也遇到了这个确切的问题,解决方法很简单。

    您的函数实际上是正确的,它只需要包装在.ready() 函数中。

    您的代码如下所示:

    jQuery(document).ready(function($){
        $('body').on( 'added_to_cart', function(){
            alert("testing!");
        });
    });
    

    【讨论】:

      【解决方案3】:

      在你的模板“functions.php”中插入这段代码

      add_action('wp_footer','SA_added_to_cart');
      function SA_added_to_cart(){?>
          <script type="text/javascript">
              // Ready state
              (function($){
      
                  $( document.body ).on( 'added_to_cart', function(){
                              alert("testing!");
                  });
      
              })(jQuery); // "jQuery" Working with WP (added the $ alias as argument)
              </script>
          <?php
      }
      

      【讨论】:

      • 您好,欢迎来到 SO。如果你回答一个问题,你必须至少解释为什么你的答案有帮助以及如何帮助。无论如何,您的建议并不能回答问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-26
      • 2016-02-10
      • 1970-01-01
      • 2021-10-01
      • 2019-02-21
      • 2014-06-09
      • 2019-10-31
      相关资源
      最近更新 更多