jQuery - noConf...LOGIN

jQuery - noConflict() method

jQuery - noConflict() method

How to use jQuery and other frameworks on the page at the same time?

jQuery and other JavaScript frameworks

As you have already learned, jQuery uses the $ symbol as shorthand for jQuery.

What if other JavaScript frameworks also use the $ symbol as a shorthand?

Some other JavaScript frameworks include: MooTools, Backbone, Sammy, Cappuccino, Knockout, JavaScript MVC, Google Web Toolkit, Google Closure, Ember, Batman, and Ext JS.

Some of these frameworks also use the $ symbol as a shorthand (just like jQuery). If you are using two different frameworks that are using the same shorthand symbol, it may cause the script to stop running.

The jQuery team took this issue into consideration and implemented the noConflict() method.

jQuery noConflict() method

The noConflict() method releases control of the $ identifier so that other scripts can use it.

Of course, you can still use jQuery by substituting the full name for the abbreviation:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$.noConflict();
jQuery(document).ready(function(){
  jQuery("button").click(function(){
    jQuery("p").text("恭喜发财!");
  });
});
</script>
</head>
<body>
<p>我要变身了!</p>
<button>点我有惊喜哦</button>
</body>
</html>

You can also create your own abbreviation. noConflict() returns a reference to jQuery that you can store in a variable for later use. Take a look at this example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
var jq=$.noConflict();
jq(document).ready(function(){
  jq("button").click(function(){
    jq("p").text("哪来这么多惊喜,好好学习了!");
  });
});
</script>
</head>
<body>
<p>我要变身了!</p>
<button>点我有惊喜哦</button>
</body>
</html>

If your jQuery code block uses $ abbreviation, and you don't want to change this shortcut, you can pass the $ symbol as a variable to the ready method. This way you can use the $ symbol inside the function - but outside the function, you still have to use "jQuery":

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$.noConflict();
jQuery(document).ready(function($){
  $("button").click(function(){
    $("p").text("学习要努力,持之以恒!");
  });
});
</script>
</head>
<body>
<p>真的有惊喜,试试</p>
<button>点我点我</button>
</body>
</html>


Next Section
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $.noConflict(); jQuery(document).ready(function(){ jQuery("button").click(function(){ jQuery("p").text("恭喜发财!"); }); }); </script> </head> <body> <p>我要变身了!</p> <button>点我有惊喜哦</button> </body> </html>
submitReset Code
ChapterCourseware