Comparison between jQuery's method to avoid conflict between $ operator and other JS Libraries
$ Is required in jQuery. If the $ symbol is also defined in other js libraries, a conflict will occur and the normal execution of js Code will be affected. Below are several good solutions, for more information, see
$ Is required in jQuery. If other js libraries (such as the famous prototype) also define the $ symbol, a conflict will occur and the normal execution of js Code will be affected. Jqeury provides some solutions to avoid this problem. Let's take a look at the differences between the solutions.
Solution 1:
Introduce noConflict () and replace $ with other symbols.
The Code is as follows:
Var $ j = jQuery. noConflict ();
$ J (document). ready (function (){
$ J ("# btn1"). click (function (){
Alert ("Text:" + $ j ("# test"). text ());
});
});
Disadvantage: after this code is introduced, it is not only the current js file, but $ j must be used to replace the previous $
Solution 2:
The ready function is the jquery entry function.
Set $ (document). ready (function (){
Replace
JQuery (document). ready (function ($ ){}
Disadvantage: it is only valid for code nested in ready and invalid for code outside the nested. If all your logic is being written into the ready function, no problem. However, we usually write some subfunctions out of the ready function, and then the ready function calls these functions. This scheme is ineffective for these functions, so this scheme has limitations.
Solution 3 (recommended, especially when developing js plug-ins ):
Package a function for js content
The Code is as follows:
JQuery (function ($ ){
// Put your js code here (for example, the ready function and subfunction mentioned in the second solution)
// If it is a js file, it is actually adding a line of code to the header and tail of the file
}
Or
The Code is as follows:
(Function ($ ){
// Your js Code
}) (JQuery );
This method does not have any disadvantages of the above two schemes. It only affects the code of the wrapped in jQuery (function ($.
It is important that other js Code is not affected. Imagine if you have written a js public component that requires jquery. To improve robustness, you need to consider the $ symbol conflict issue. If solution 1 is used, you must follow your conventions to change $ in your js Code to $. If solution 3 is used, this avoids the impact of $ conflict on the component, and does not require people who use public components to modify their own code.