jQuery 学习笔记 避免冲突

℡╲_俬逩灬. 提交于 2019-12-31 03:57:54

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>

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!