简体   繁体   English

如何将jquery转换为noconflict?

[英]How to convert jquery into noconflict?

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.我在 Wordpress 站点上遇到了一个问题,其中主题有一个很大的init.js文件,该文件似乎导致与某些插件发生冲突。

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.免责声明,我完全是个菜鸟,但我想我需要将下面的代码块转换为noconflict模式,但我尝试过的几件事似乎不起作用。

jQuery(document).ready(function(){

    $ = jQuery; 

Is it possible to convert that code into noconflict?是否可以将该代码转换为无冲突?

You can use IIFE to do that:您可以使用IIFE来做到这一点:

 (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:如果你使用 webpack,你可能需要先检查全局对象:

 (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. noConflict() 方法返回对 jQuery 的引用,您可以将其保存在变量中,以备后用。

 <!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.comW3schools.com 中所述

You have add jQuery.noConflict() after ready function and then start your logic.您已经在就绪函数之后添加了jQuery.noConflict() ,然后开始您的逻辑。 Example:例子:

jQuery(document).ready(function(){ jQuery(文档).ready(函数(){

$ = jQuery;
$.noConflict();

//Your logic //你的逻辑

}); });

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

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