Avoiding Conflicts with Other Libraries
jQuery默认使用$作为它的命名空间快捷方式,为了避免jQuery与其他库的命名冲突,jQuery官方给了以下几个解决方案
1.产生一个别名
1 <!-- Putting jQuery into no-conflict mode. -->
2 <script src="prototype.js"></script>
3 <script src="jquery.js"></script>
4 <script>
5
6 var $j = jQuery.noConflict();
7 // $j is now an alias to the jQuery function; creating the new alias is optional.
8
9 $j(document).ready(function() {
10 $j( "div" ).hide();
11 });
12
13 // The $ variable now has the prototype meaning, which is a shortcut for
14 // document.getElementById(). mainDiv below is a DOM element, not a jQuery object.
15 window.onload = function() {
16 var mainDiv = $( "main" );
17 }
18
19 </script>
jQuery.noConflict() 方法会返回jQuery 函数的引用,所以可以使用任何你喜欢的变量
2运用一个即时调用函数表达式
1 <!-- Using the $ inside an immediately-invoked function expression. -->
2 <script src="prototype.js"></script>
3 <script src="jquery.js"></script>
4 <script>
5
6 jQuery.noConflict();
7
8 (function( $ ) {
9 // Your jQuery code here, using the $ ,但是在这里不能使用$来代替其他的库
10 })( jQuery );
11
12 </script>
3将参数传递给 jQuery( document ).ready() 函数
1 <script src="jquery.js"></script>
2 <script src="prototype.js"></script>
3 <script>
4
5 jQuery(document).ready(function( $ ) {
6 // Your jQuery code here, using $ to refer to jQuery.
7 });
8
9 </script>
在这里jQuery库要在其他库之前声明
4使用更简洁的DOM ready 写法
<script src="jquery.js"></script>
<script src="prototype.js"></script>
<script>
jQuery(function($){
// Your jQuery code here, using the $
});
</script>
来源:https://www.cnblogs.com/xviubu/p/3438607.html