Is there a way turn off jQuery noConflict mode in

2019-01-15 06:50发布

问题:

Is there a way turn off jQuery.noConflict in WordPress? I don't mean loading an alternative version of jQuery or changing the loading method ie:

jQuery(document).ready(function( $ ) { ... });

or

(function($) { ... })( jQuery );

I mean is there a way to just turn off noConflict mode for the version of jQuery bundled with WordPress?

Like would setting jQuery.noConflict(false) work? If so, where would you set it?

回答1:

After some research, this is the best answer I can give you:

$ = jQuery.noConflict(true);

To answer your other question, no you can't pass in false, the attribute is used to control what happens to global variables. You can find the documentation here: http://api.jquery.com/jQuery.noConflict/

Also note you could load 2 different versions of jQuery as it suggests (but is not recommended).



回答2:

If you are including your own javascript library or scripts you can add the following to the very top:

 var $ = jQuery;


回答3:

I found another way of making the variable $ available globally. Just put the following in your theme's functions.php or in a plugin:

function so17687619_jquery_add_inline() {
    wp_add_inline_script( 'jquery-core', '$ = jQuery;' );
}
add_action( 'wp_enqueue_scripts', 'so17687619_jquery_add_inline' );

This will output $ = jQuery; as an inline script immediately after the script tag for jQuery. So any scripts included after have the jQuery instance available as $ and jQuery.



回答4:

To turn if off go to your wp-includes/js/jquery/jquery.js file and remove the jQuery.noConflict() from the last line. Or as you suggested just set the boolean to false.

That or you could replace the contents with a clean download from jquery.com, there is an intense debate going on in the trac.



回答5:

Adding this worked for me finally:

var $ = jQuery.noConflict();

You can add this in your header.php file in the head section:

<script>var $ = jQuery.noConflict();</script>

Or if you use child theme, add that to functions.php in your child theme directory:

function my_scripts_method() {
    wp_enqueue_script(
        'custom-script',
        get_stylesheet_directory_uri() . '/main.js',
        array( 'jquery' )
    );
}
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );

And create a main.js file in the same location as functions.php (in the child theme direcotry) and in that file add this:

var $ = jQuery.noConflict();