I have an issue on a Wordpress site where the theme has a large init.js
file that seems to be causing conflicts with some plugins.
Disclaimer, I'm a total noob, but I'm thinking that I would need to convert the below chunk of code into noconflict
mode, but the few things that I have tried do not seem to work.
jQuery(document).ready(function(){
$ = jQuery;
Is it possible to convert that code into noconflict?
You can use IIFE to do that:
(function ($) { console.log(typeof $); $(document).ready(function () { console.log($('body')[0]); }); })(typeof $ === 'function' ? $ : jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you're using webpack, you may need to check global object first:
(function (global, factory) { factory(typeof global.$ === 'function' ? global.$ : global.jQuery); })(typeof window === 'object' ? window : this, function ($) { console.log(typeof $); $(document).ready(function () { console.log($('body')[0]); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can also create your own shortcut very easily. The noConflict() method returns a reference to jQuery, that you can save in a variable, for later use.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> var jq = $.noConflict(); jq(document).ready(function(){ jq("button").click(function(){ jq("p").text("jQuery is still working!"); }); }); </script> </head> <body> <p>This is a paragraph.</p> <button>Test jQuery</button> </body> </html>
As Described in W3schools.com
You have add jQuery.noConflict()
after ready function and then start your logic. Example:
jQuery(document).ready(function(){
$ = jQuery;
$.noConflict();
//Your logic
});
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.