解决WooCommerce购物车点击加号按钮后ajaxStop多次触发问题
解决WooCommerce购物车ajaxStop重复触发提示的问题
问题根源很明确:你当前的代码每次点击加号且商品数量达到库存上限时,都会给document绑定一个新的ajaxStop事件处理函数。多次点击后,Ajax完成时所有绑定的函数都会执行,自然就导致提示信息重复显示。
下面给你两种可行的解决办法:
方案1:使用one()绑定单次事件
one()方法会让事件处理函数仅执行一次,执行后自动解绑,不会重复触发。修改后的代码如下:
jQuery(document).on('click', '.plus.button.is-form', function(e) { var $quantityDiv = jQuery(this).closest('div.quantity.buttons_added'); var inputval = $quantityDiv.find('input[name^="cart"]').val(); var inputmax = $quantityDiv.find('input[name^="cart"]').attr('max'); if (inputval == inputmax) { // 使用one()确保事件只执行一次 jQuery(document).one('ajaxStop', function() { alert("TeSZT"); jQuery('.woocommerce-notices-wrapper').html('<div class="woocommerce-info"><div class="woocommerce-info-text">Sajnos ebből a termékből jelenleg nincs több raktáron</div><span class="close-message"></span></div>'); }); } });
方案2:使用命名空间事件,绑定前先解绑
给事件添加专属命名空间,每次绑定前先移除同命名空间的事件,避免重复绑定:
jQuery(document).on('click', '.plus.button.is-form', function(e) { var $quantityDiv = jQuery(this).closest('div.quantity.buttons_added'); var inputval = $quantityDiv.find('input[name^="cart"]').val(); var inputmax = $quantityDiv.find('input[name^="cart"]').attr('max'); if (inputval == inputmax) { // 先解绑同命名空间的事件,再绑定新的 jQuery(document).off('ajaxStop.cartStockNotice').on('ajaxStop.cartStockNotice', function() { alert("TeSZT"); jQuery('.woocommerce-notices-wrapper').html('<div class="woocommerce-info"><div class="woocommerce-info-text">Sajnos ebből a termékből jelenleg nincs több raktáron</div><span class="close-message"></span></div>'); }); } });
额外优化:代码里缓存了$quantityDiv对象,避免重复查找DOM元素,能小幅提升页面性能。
内容的提问来源于stack exchange,提问作者Simulator88
相关产品推荐
相关产品推荐

