jquery requires the word Jquery instead of $ [dupl

2019-09-19 09:44发布

问题:

This question already has an answer here:

  • jQuery ready function doesn't work in WordPress 3 answers

I am working on a WordPress theme and I have included Jquery,

    // Waves
    wp_enqueue_style( 'APKMirror-wave', get_template_directory_uri() . '/inc/waves/waves.min.css');
    wp_enqueue_script(
        'APKMirror-wave',
        get_stylesheet_directory_uri() . '/inc/waves/waves.min.js',
        array( 'jquery' )
    );

    // Boostrap
    wp_enqueue_style( 'APKMirror-Bootstrap', get_template_directory_uri() . '/inc/bootstrap/bootstrap.min.css');
    wp_enqueue_script(
        'APKMirror-Bootstrap',
        get_stylesheet_directory_uri() . '/inc/bootstrap/bootstrap.min.js',
        array( 'jquery' )
    );

The problem is any time I run jQuery code I have to type the word 'jQuery' instead of just using the $. How can I change my code so that it will use $?

回答1:

jQuery in WordPress runs in noConflict mode which means the global $ shortcut for jQuery isn't available. Use the document ready wrapper which will allow $ to be used as an alias for jQuery.

jQuery(document).ready(function($) {
    // Inside here $ can be used instead of jQuery.
});

Or

(function($) {
    // Use $ here.
})(jQuery);

Thanks to Paulpro for correctly pointing out that there is an alternative that can be used if you need to run the script before the rest of the DOM loads.