jQuery - noConflict() method
jQuery uses the $ symbol as shorthand for jQuery.
What if other JavaScript frameworks also use the $ symbol as a shorthand?
Some other JavaScript frameworks include: MooTools, Backbone, Sammy, Cappuccino, Knockout, JavaScript MVC, Google Web Toolkit, Google Closure, Ember, Batman, and Ext JS.
Some of these frameworks also use the $ symbol as a shorthand (just like jQuery). If you are using two different frameworks that are using the same shorthand symbol, it may cause the script to stop running.
The jQuery team took this issue into consideration and implemented the noConflict() method.
The role of noConflict()
noConflict() exists for only one purpose: it allows you to load multiple jQuery instances on the same page, especially Different versions of jQuery. You may be wondering, why do you need to load/use multiple different versions of jQuery objects on one page? Generally speaking, there are two situations. In the first case, your business code uses the latest version of the jQuery library, and the third-party plug-in you choose relies on an earlier version of the jQuery library; in the second case, you are maintaining a system that already has business For various reasons, the code references an older version of the jQuery library, and your newly developed module uses other versions of the jQuery library. In either case, you have to face the problem of jQuery object/method conflicts. Fortunately, jQuery.noConflict() helps you solve this trouble.
jQuery noConflict() method
The noConflict() method releases control of the $ identifier so that other scripts can use it.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script> $.noConflict(); jQuery(document).ready(function(){ jQuery("button").click(function(){ jQuery("p").text("jQuery在工作!"); }); }); </script> </head> <body> <p>看我的变化</p> <button>点我</button> </body> </html>
Use jQuery by replacing the abbreviation with the full name.
You can create your own abbreviation:
var jq = $.noConflict(); jq(document).ready(function(){ jq("button").click(function(){ jq("p").text("jQuery 仍然在工作!"); }); });
If your jQuery code block uses $ abbreviation and you are unwilling to change this shortcut, you can pass the $ symbol as a variable to the ready method. This way you can use the $ symbol inside the function - but outside the function, you still have to use "jQuery":
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script> $.noConflict(); jQuery(document).ready(function($){ $("button").click(function(){ $("p").text("这是覆盖的文字"); }); }); </script> </head> <body> <p>这是一段文字</p> <button>点击显示</button> </body> </html>