避免在 WooCommerce 购物车中单击按钮时仅运行一次的功能

Avoid a function to only runs once on button click in WooCommerce cart

每次单击 update_cart 按钮时,我都在尝试 运行 函数 cart_refresh_update_qty,但它只在第一次起作用,如果我再次更新购物车,它就不会起作用运行 再次,我需要重新加载页面吗?

这是我的 WordPress 子主题功能文件中的一些自定义代码。

<?php
//
// Recommended way to include parent theme styles.
//  (Please see http://codex.wordpress.org/Child_Themes#How_to_Create_a_Child_Theme)
//  
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( 'child-style',
    get_stylesheet_directory_uri() . '/style.css',
    array('parent-style')
    );
}
// register add to cart action
    add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_add_to_cart', 10 );
/*
global $product;       
if ( in_category('listone-sample')) {   
    add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_add_to_cart', 10 );
}
*/

add_action( 'woocommerce_before_shipping_calculator', 'cart_refresh_update_qty',10); 
function cart_refresh_update_qty() { 
   if (is_cart()) { 
      ?> 
      <script type="text/javascript"> 
     jQuery("input[name = 'update_cart']").on('click', function(){ 
         alert('Cart Qty Changed, Shipping total will be updated.');
     jQuery("[name='calc_shipping']").trigger("click"); 
    }); 
     </script> 
     <?php 
   } 
}
?>

我没有看到任何错误消息。

改为使用以下内容作为 document.body 委托事件:

add_action( 'wp_footer', 'cart_refresh_update_qty');
function cart_refresh_update_qty() {
    if (is_cart()) :
    ?>
    <script type="text/javascript">
    jQuery( function($){
        $(document.body).on('click', 'button[name="update_cart"]', function(){
            console.log('Cart Qty Changed, Shipping total will be updated.');
            $('button[name="calc_shipping"]').trigger('click');
        });
    });
    </script>
    <?php
    endif;
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。测试和工作。

现在不仅运行第一次……