Quick way to resolve conflicts between JQuery's $and other JS

  • 2020-03-30 01:25:46
  • OfStack

As we all know, jQuery is the most popular JS package at present, which simplifies many complex JS programs. JQuery defines the browser DOM tree as $, and gets each child node through $.

However, JQuery is not the only JS plug-in, there are other good plugins such as prototype.js. They also use $. So sometimes when you use the two JS plug-ins at the same time, there will be a conflict in the use right of $. Now let's look at how to solve this conflict problem. See below:

We all know that JQuery has a function, jquery.noconflict (), which transfers control of $. Then we can use jQuery instead of $to get the dom node

For example:

Method one:


<script type="text/javascript">
jQuery.noConflict(); //Cede control of the variable $to prototype.js
jQuery(function(){ //Using jQuery
jQuery("p").click(function(){
alert( jQuery(this).text() );
});
});
$("pp").style.display = 'none'; //Using the prototype
</script>

Method 2:

We can use the noConflict() function to define a shortcut to get dom nodes


<script type="text/javascript">
var $j = jQuery.noConflict(); //Customize a short shortcut
$j(function(){ //Using jQuery
$j("p").click(function(){
alert( $j(this).text() );
});
});
$("pp").style.display = 'none'; //Using the prototype
</script>

There are other methods, are listed for you, the same can see it, ah.

Method 3:


<script type="text/javascript">
jQuery.noConflict(); //Cede control of the variable $to prototype.js
jQuery(function($){ //Using jQuery
$("p").click(function(){ //Continue with the $method
alert( $(this).text() );
});
});  
$("pp").style.display = 'none'; //Using the prototype
</script>

Method 4:

<script type="text/javascript">
jQuery.noConflict(); //Cede control of the variable $to prototype.js
(function($){ //Define the anonymous function and set the parameter to $
$(function(){ //The $inside the anonymous function is jQuery
$("p").click(function(){ //Continue with the $method
alert($(this).text());
});
});
})(jQuery); //Executes anonymous functions and passes arguments to jQuery
$("pp").style.display = 'none'; //Using the prototype
</script>


Related articles: