jQuery resolves $symbol naming conflicts

  • 2021-06-29 09:33:15
  • OfStack

A few days ago, my friend asked me to help him solve the compatibility problem of the jquery special effect on one page, which is an easy and important point to ignore, and I write it down here.

Three special effects were used in the page given by a friend, two of which could be shown and the third one had no effect.By looking at the referenced js file, I see that not only has jquery.js been introduced to the page, but also a file named prototype.js has been introduced.This prototype.js has not been heard before, and has been purposefully searched in Baidu. Originally, it is also an js class library, which has similar functions as jquery and is very powerful.

From a point-by-point survey, I found that the two special effects that can be displayed refer to jquery, while the one that is not displayed refers to prototype.js.After a little analysis, the key to the error was found: the $in jquery conflicts with the $in prototype.js, and both libraries are called with the $symbol. However, if you write this directly, you will not know who the $belongs to and which method in the class library should be called to achieve special effects.

Now that you have found the root of the problem, it will be solved.

Method 1: In jquery, there is a piece of code like this:


// Expose jQuery to the global object

window.jQuery = window.$ = jQuery;

That is, we can use jQuery instead of the $symbol in jquery.js if we declare 1:

jQuery = $;

Then a new problem arises.There are so many places on the page where you use $, I don't just want to distinguish which $belongs to jquery, but also replace them with the word jQuery. More importantly, if you want to add a new jquery special effect to the page, I'll always remind myself that when you call $, you need to use jQuery instead. Just neglect, you'll not only get the effect you don't want.It is also a heavy task to modify.It seems that this method is not feasible.

Isn't there a way to make a clear distinction between this $right of attribution?Of course there is a way!

Method 2: Use the jquery statement block to implement:

First, let's look at the format of the jquery statement block:


(function($){ 
 ..... 
 $('#msg').show();// All used in this statement block are jquery.js Defined in $. 

})(JQuery)

This way, when we call $in jquery for special effects display, just write this code in this statement block and how to call the $symbol.The $symbol in prototype.js is written outside the statement block, and how to call it does not matter at all.


Related articles: