The $ symbol needs to be used in jQuery. If other js libraries (such as the famous prototype) also define the $ symbol, it will cause a conflict and affect the normal execution of the js code. jqeury provides some solutions to avoid this problem. Let’s take a look at the differences between these solutions
Option 1:
Introduce noConflict() and replace $ with other symbols
var $j = jQuery.noConflict();
$j(document ).ready(function(){
$j("#btn1").click(function(){
alert("Text: " $j("#test").text());
});
});
Disadvantages: After introducing this code, not only the current js file, but also all the js referenced by the html, if useful in jquery $, must use $j to replace the previous $
Option 2:
ready function is the entry function of jquery, you can
change $(document).ready(function(){
Replace with
jQuery(document).ready(function($){}
Disadvantages: It is only valid for the code inside the ready nest, and is invalid for the code outside the nest. If all your logic, It's all in the ready function, that's no problem. But we usually write some sub-functions outside the ready function, and then the ready function calls these functions. This solution is invalid for these functions, so this solution has limitations. .
Option 3 (recommended, especially when developing js plug-ins):
Add a function to the js content package
jQuery(function($){
//Put your js code here (for example, the ready mentioned in the second solution Functions and sub-functions)
//If it is a js file, actually add a line of code at the beginning and end of the file
}
or
(function($) {
//Your js code
})(jQuery );
This method does not have the shortcomings of the above two solutions. It will only affect the code wrapped in jQuery(function($){}.
will not affect other js Code, this is very important. Just imagine, if you write a js public component, which needs to use jquery, in order to improve robustness, you need to consider the $ symbol conflict. If you use option 1, then when others use it, they have to abide by your agreement and change the $ in their js code to $. If you use option 3, you can avoid the impact of the $ conflict on the component without requiring the use of it. People with public components modify their own code.