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

<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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值