如何避免jquery库和其它库的冲突

来源:互联网 发布:2016好听的网络红歌 编辑:程序博客网 时间:2024/04/30 03:05

<span style="font-family: Verdana, Arial, Helvetica, sans-serif; line-height: 20.7999992370605px; background-color: rgb(255, 255, 255);">1.产生原因:</span>

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

2.解决方法:

JQuery库在其他库之后导入——

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

<!-- Loading jQuery before other libraries --><script src="jquery.js"></script><script src="prototype.js"></script><script> <span style="white-space:pre"></span>JQuery.noConflict();    // Use full jQuery function name to reference jQuery    jQuery(document).ready(function(){     jQuery("div").hide();   });     // Use the $ variable as defined in prototype.js    window.onload = function() {   var mainDiv = $('main');  }; </script>
方法2:声明一个新的变量,来代替$。
<!-- Putting jQuery into no-conflict mode --><script src="prototype.js"></script><script src="jquery.js"></script><script>    // $j is now an alias to the jQuery function;    // creating the new alias is optional    var $j = jQuery.noConflict();    $j(document).ready(function(){       $j("div").hide();     });     // The $ variable now has the prototype meaning,    // which is a shortcut for document.getElementById.    // mainDiv below is a DOM element, not a jQuery object    window.onload = function(){       var mainDiv = $('main');    }</script>

如果不想给JQquery自定义这些备用名称,还想使用$而不管其他库的$()方法,同时又不想与其他库冲突,那么可以使用一下两种解决方法。

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

<!-- Another way to put jQuery into no-conflict mode --><script src="prototype.js"></script><script src="jquery.js"></script><script>     jQuery.noConflict();    jQuery(document).ready(function($){       // You can use the locally-scoped $ in here as an alias to jQuery       $("div").hide();     });     // The $ variable in the global scope has the prototype.js meaning    window.onload = function(){       var mainDiv = $('main');    } </script>

方法4:

JQuery.noConflict();(function($){  (function($){     $("p").click(function(){        alert("$(this).text());     })  })})(JQuery);$("pp").style.display='none';
JQuery库在其他库之前导入——

<script src="../JQuery/jquery.js" type="text/javascript"></script><script src="../lib/prototype.js" type="text/javascript"></script>
有了这些方法解决冲突,就可以在项目中放心的引用JQuery了。

0 0
原创粉丝点击