简体   繁体   English

在 ajax 添加到 Woocommerce 中的购物车事件后运行 javascript 代码

[英]Run javascript code after ajax add to cart event in Woocommerce

In woocommerce I have an add to cart button with the following classes:在 woocommerce 中,我有一个包含以下类的添加到购物车按钮:

button product_type_simple add_to_cart_button ajax_add_to_cart 

I want to run a javascript code once this button has been clicked.单击此按钮后,我想运行 javascript 代码。 It is a custom JS file.它是一个自定义的 JS 文件。 How can I trigger my custom js file when this class is clicked?单击此类时如何触发自定义 js 文件?

Try the following code where you can trigger some code on ajax add to cart, once product is added to cart:尝试下面的代码,一旦产品添加到购物车,您就可以在其中触发一些关于 ajax 添加到购物车的代码:

add_action( 'wp_footer', 'trigger_for_ajax_add_to_cart' );
function trigger_for_ajax_add_to_cart() {
    ?>
        <script type="text/javascript">
            (function($){
                $('body').on( 'added_to_cart', function(){
                    // Testing output on browser JS console
                    console.log('added_to_cart'); 
                    // Your code goes here
                });
            })(jQuery);
        </script>
    <?php
}

Code goes in function.php file of the active child theme (or active theme).代码进入活动子主题(或活动主题)的 function.php 文件。 Tested and works.测试和工作。

If you need to access JQuery, you need to add a hook for a click on all the elements with that class. 如果您需要访问JQuery,则需要添加一个钩子来点击该类的所有元素。 .click() Documentation . .click()文档

Basically what you need to do is the following: 基本上你需要做的是以下几点:

$('.button').click(function(event){
// your code here
});

Where $() is calling jQuery, '.button' is saying all the elements with class ('.') 'button', and .click is adding a handler on each click event on those items. 其中$()调用jQuery,'。button'表示所有带有类('。')'按钮'的元素,而.click正在为这些项上的每个click事件添加一个处理程序。 Read documentation for further explanation + there are a lot of questions on this subject already so most information is either in docs or in stackoverflow\\google. 阅读文档以获得进一步说明+已经有很多关于此主题的问题,因此大多数信息都在docs或stackoverflow \\ google中。

Good luck! 祝好运!

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

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