A way to let jQuery coexist with other JavaScript libraries to avoid collisions

  • 2020-03-30 01:02:35
  • OfStack

In order to resolve the conflict between jQuery and the $() function in other JavaScript libraries, it is necessary to cancel the $() function of jQuery, for which jQuery provides the following methods:
//Cancels the $() function in jQuery
jQuery.noConflict() ; 

Place the above bold code on the first line of JavaScript code, which cancels jQuery's $() function

Note: the $() alias for the jQuery() function is simply removed, so we can still use jQuery instead of the original $().

In addition, writing jQuery() multiple times is cumbersome, and jQuery also allows developers to specify their own aliases for jQuery(), as shown in the following code:
<div id="lee"></div> 
<script type="text/javascript" src="../jquery-1.10.2.js"> 
<script type="text/javascript"> 
//Give the jQuery() function the alias lee
var lee = jQuery.noConflict() ; 
var target = lee("#lee") 
target.html(" I want to learn JQuery") 
.css("border" , "2px solid black") 
.css("background-color" , "#ddddff") 
.css("padding" , 20) ; 

Related articles: