绑定完请刷新页面
取消
刷新

分享好友

×
取消 复制
如何避免jquery库和其它库的冲突
2020-01-07 18:06:32

1.产生原因:

默认情况下:jQuery使用 $ 作为jquery的快捷方式,如果别的js库也使用$的话,就可能产生冲突。为避免这种冲突,需要在把jquery引入页面后,使用jquery前把jquery设置为非冲突模式。

2.解决方法:

  方法1:使用jquery的命名空间,当然就不会冲突了。

复制代码
 1 <!-- Loading jQuery before other libraries -->
 2 <script src="https://image.z.itpub.net/zitpub.net/JPG/2020-01-07/7953A166851B4791B012BC16D2FEF0AA.jpg"></script>
 3 <script src="https://image.z.itpub.net/zitpub.net/JPG/2020-01-07/0030C3E398B96D1C02007521FBC8C642.jpg"></script>
 4 <script>
 5  
 6     // Use full jQuery function name to reference jQuery
 7     jQuery(document).ready(function(){
 8      jQuery("div").hide();
 9    });
10  
11     // Use the $ variable as defined in prototype.js
12     window.onload = function() {
13    var mainDiv = $('main');
14   };
15  
16 </script>
复制代码

 

  方法2:声明一个新的变量,来代替$。

复制代码
 1 <!-- Putting jQuery into no-conflict mode -->
 2 <script src="https://image.z.itpub.net/zitpub.net/JPG/2020-01-07/0030C3E398B96D1C02007521FBC8C642.jpg"></script>
 3 <script src="https://image.z.itpub.net/zitpub.net/JPG/2020-01-07/7953A166851B4791B012BC16D2FEF0AA.jpg"></script>
 4 <script>
 5     // $j is now an alias to the jQuery function;
 6     // creating the new alias is optional
 7     var $j = jQuery.noConflict();
 8     $j(document).ready(function(){
 9        $j("div").hide();
10      });
11  
12     // The $ variable now has the prototype meaning,
13     // which is a shortcut for document.getElementById.
14     // mainDiv below is a DOM element, not a jQuery object
15     window.onload = function(){
16        var mainDiv = $('main');
17     }
18 </script>
复制代码

  方法3:给ready()方法增加一个参数。比较常用此方法。

复制代码
 1 <!-- Another way to put jQuery into no-conflict mode -->
 2 <script src="https://image.z.itpub.net/zitpub.net/JPG/2020-01-07/0030C3E398B96D1C02007521FBC8C642.jpg"></script>
 3 <script src="https://image.z.itpub.net/zitpub.net/JPG/2020-01-07/7953A166851B4791B012BC16D2FEF0AA.jpg"></script>
 4 <script>
 5  
 6     jQuery.noConflict();
 7     jQuery(document).ready(function($){
 8        // You can use the locally-scoped $ in here as an alias to jQuery
 9        $("div").hide();
10      });
11  
12     // The $ variable in the global scope has the prototype.js meaning
13     window.onload = function(){
14        var mainDiv = $('main');
15     }
16  
17 </script>
复制代码

 

 

 

 

 

 

 

 

分享好友

分享这个小栈给你的朋友们,一起进步吧。

JAVA玩具小屋
创建时间:2019-08-16 16:54:49
分享程序开发方面的小经验,思考一些比较简单易懂的技术问题
展开
订阅须知

• 所有用户可根据关注领域订阅专区或所有专区

• 付费订阅:虚拟交易,一经交易不退款;若特殊情况,可3日内客服咨询

• 专区发布评论属默认订阅所评论专区(除付费小栈外)

栈主、嘉宾

查看更多
  • Yios5092
    栈主

小栈成员

查看更多
  • 栈栈
  • coyan
  • 25minutes
  • ?
戳我,来吐槽~