简体   繁体   中英

WooCommerce global.js doesn't work after update cart

I write personnal javascript in global.js , and it work until I click on the WooCommerce button update_cart .

After my function doesn't work.

The function is for update notification display :

    $('#nb_article').change(function() {
        if ($('#nb_article').text() = 0) {
            $('#nb_article').css("display", "none");
        } else {
            $('#nb_article').css("display", "block");
        }
    });

and it's in balise jQuery(document).ready(function($) {} .

Do you know what can I do ?

The update cart action is triggered on woocommerce/assets/js/frontend/cart.js , look for update_cart: function() {

It makes a ajax call to the url of form and then update the .woocommerce div with the html returned by ajax call. So, it doesn't work maybe because $('#nb_article') is inside .woocommerce and the plugin will replace all html, losing the events. You should reapply the event handler after update.

Or in alternative, you can apply the event by delegation, in this way:

$('.woocommerce').on( 'change', '#nb_article', function() {
    var $nb_article = $(this);

    if ( $nb_article.text() == 0) {
        $nb_article.css("display", "none");
    } else {
        $nb_article.css("display", "block");
    }
});

There are two issues:

  1. inside event function, you have to use $(this) so you can refer to element that triggers the event

  2. in the if statement you have to use the compare operator == instead of =

So the final results should be:

$('#nb_article').change(function() {
    var $nb_article = $(this);

    if ( $nb_article.text() == 0) {
        $nb_article.css("display", "none");
    } else {
        $nb_article.css("display", "block");
    }
});

They are surely issues, but I don't know if there is something other related to other code of your project.

I hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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