This article mainly introduces how to use $ in jQuery to avoid conflicts with other libraries. There are three methods listed in total. For more information, see Jquery, $ is the alias of JQuery. You can use JQuery to replace $. For example, $ ('# msg') is equivalent to JQuery ('# msg. However, when we introduce multiple js libraries and define the $ symbol in another js library, we will encounter a conflict when using the $ symbol. The following describes how to introduce two library files: jquery. js and prototype. js.
First case: jquery. js is introduced after prototype. js, for example:
In this case, we write the following in our own js Code:
$('#msg').hide();
$ Always represents the $ symbol defined in jquery, and can also be written as JQuery ('# msg '). hide (); if you want to use prototype. $ defined in js. We will introduce it later.
Case 2: jquery. js is introduced before prototype. js, for example:
In this case, we write the following in our own js Code:
$('#msg').hide();
$ Prototype. $ symbol defined in js. If we want to call jquery. if the factory in js selects the function, it can only be written in the full name JQuery ('# msg '). hide ().
The following describes how to correctly use the $ symbol defined in different js libraries when the file sequence of the first js library is introduced.
I. Use JQuery. noConflict ()
The function of this method is to let Jquery give up its ownership of $ and return the control of $ to prototype. js, because jquery. js is introduced later, so jquery is the final control of $. The returned value is JQuery. After the method is called in the code, we cannot use $ to call the jquery method. $ represents the $ defined in the prototype. js library. As follows:
JQuery. noConflict (); // You cannot write $ ('# msg'). hide () here. $ represents the $ symbol defined in prototype. js. JQuey ('# msg'). hide ();
Since then, $ represents the $ defined in prototype. js. $ in jquery. js cannot be used any more. You can only use the full name of $ in jquery. js.
After setting jQuery to no-conflict mode, you can set an alias for $: