jquery函数在一个页面中工作但在其他页面中不具有相同的属性(但它在控制台上工作)

时间:2017-02-24 21:29:50

标签: javascript jquery html wordpress woocommerce

我在这里非常奇怪。我试图在wordpress woocommerce结帐页面中用jquery隐藏两个元素。它是这样的(伪代码):

if (#id) is >= 1 
    then hide (elements)
else
    show (elements)

我的代码就是这个:

jQuery(document).ready(function () { 
    if (jQuery('#shipping_method_0_free_shipping6').length >= 1 ) { 
        jQuery('[for="shipping_method_0_flat_rate8"]').hide();
        jQuery('[value="flat_rate:8"]').hide();
    } else { 
        jQuery( "#shipping_method_0_flat_rate8" ).show() && jQuery(".woocommerce-Price-amount.amount").show(); 
}
});

奇怪的是,如果我在代码块上添加脚本,但是当我在“checkout”页面上添加脚本时,这在woocommerce的“购物车”页面上运行良好,在页面加载时工作但是页面很快是完全加载,元素再次显示...一些想法为什么或一些sugestions?

非常感谢您花时间看看!

1 个答案:

答案 0 :(得分:3)

在WooCommerce中,结帐由Ajax生成。因此,当页面加载时,结果会像其他每个元素一样生成,然后文档就绪事件触发,然后WooCommerce使用ajax重新加载结帐。所以基本上你的jQuery代码只适用于checkout的第一次加载,它会被Ajax立即覆盖。

要解决此问题,您可以在updated_checkout事件上运行一个函数,WooCommerce会添加该函数。像这样:

jQuery('body').on('updated_checkout', function() {
     if (jQuery('#shipping_method_0_free_shipping6').length >= 1 ) { 
         jQuery('[for="shipping_method_0_flat_rate8"]').hide();
         jQuery('[value="flat_rate:8"]').hide();
     } else { 
         jQuery( "#shipping_method_0_flat_rate8" ).show() && jQuery(".woocommerce-Price-amount.amount").show(); 
     }
}
相关问题