简体   繁体   English

ajaxComplete多次激活 - woocommerce加入购物车

[英]ajaxComplete firing multiple times - woocommerce add to cart

I am trying to make an alert window fire when adding specific products to cart in WooCommerce. 我想在WooCommerce中将特定产品添加到购物车时发出警报窗口。 For this I am adding a click function to the add to cart button, that fires on ajaxComplete. 为此,我将添加一个单击功能到添加到购物车按钮,该按钮在ajaxComplete上触发。 However, the ajaxComplete seems to make it fire multiple times. 但是,ajaxComplete似乎会多次触发它。 How can I prevent this? 我怎么能阻止这个?

jQuery('#bvbutton').click(function() {
  jQuery( document ).ajaxComplete(function() {
    alert("testing!");
  });
});

EDIT: Per request here is a more thorough explanation: The ajax call is made from within WooCommerce and I would prefer not editing this. 编辑:这里的每个请求是一个更彻底的解释:ajax调用是从WooCommerce内部进行的,我不想编辑它。 What I am trying to do is giving the buttons of the specific products a unique id, and making a click on a button with this id trigger an alert box. 我想要做的是给特定产品的按钮一个唯一的ID,并点击一个具有此ID的按钮触发一个警告框。

The whole point is that items from within in a specific category, a, is supposed to give 10 % percent discount on products from category b. 重点是来自特定类别a内的物品应该对b类产品提供10%的折扣。 When adding a product from category a, the alert box is supposed to fire and inform about discount on category b. 从类别a添加产品时,警报框应该触发并通知类别b的折扣。 Hence I give these buttons a specific id, and would like to make a click event targeting these id's. 因此,我为这些按钮指定了一个特定的ID,并希望针对这些ID创建一个点击事件。 When clicked, I need to await the ajax call that adds item to cart and then fire alert box. 点击后,我需要等待ajax调用,将项目添加到购物车,然后点火警告框。

Hope it makes sense now 希望现在有意义

$.ajaxComplete is global. $.ajaxComplete是全局的。 This handler will be added to all AJAX requests as many times as is called. 此处理程序将被调用多次添加到所有AJAX请求中。 In your case each time #bvbutton is clicked a another handler instance is added globally. 在您的情况下,每次单击#bvbutton全局添加另一个处理程序实例。

Instead, add the handler once in the DOM ready event. 相反,在DOM ready事件中添加一次处理程序。 Not on any specific click events. 不是任何特定的点击事件。

$(function() {
  jQuery( document ).ajaxComplete(function() {
    alert("testing!");
  });
});

Personally I wouldn't do it this way as this will affect all AJAX operations that you do. 就个人而言,我不会这样做,因为这会影响你所做的所有AJAX操作。 I would be more inclined to use trigger to fire a custom event when that particular AJAX process is successful. 当特定的AJAX过程成功时,我更倾向于使用trigger来触发自定义事件。 That way you can be more precise as to when your alert goes off. 通过这种方式,您可以更准确地了解警报何时消失。 Here's an example: 这是一个例子:

jQuery(document).on('product-added', function () {
  console.log('Product added');
});

jQuery('#bvbutton').click(function() {
  jQuery.ajax({
     url: endpoint,
     type: 'POST',
     ...
   }).success(function (data) {
     // process data
     jQuery(document).trigger('product-added');
   });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM