Woocommerce – added_to_cart触发器

我正在尝试使用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 ] ); 

所以我也遇到了这个问题,修复很简单。

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

你的代码看起来像这样:

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

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

我通过在Storefront演示页面上的Chrome控制台运行它来测试它,可在此处找到: http : //demo2.woothemes.com/storefront/shop/ 。 只有当’radios’产品添加到购物篮时,它才会显示警告消息,它会从产品的父

  • 上的类中找到类别。

     $ = 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]; });