jQuery从入门到精通 - 避免和其它JS框架冲突

 

由于jQuery以及依赖jQuery的插件都被放置在jQuery的命名空间下。一般而言,全局对象也会放在jQuery的命名空间下。

因此一般而言,在同一个页面同时使用jQuery和其它的JS框架(prototype.js、MooTools或者是YUI),是不会产生冲突的。

即便如此,这里有一点需要注意,默认jQuery使用$来作为“jQuery”的简写,如果其它的JS框架使用$作为变量,这将可能导致和jQuery冲突。为了避免这样的冲突,你需要设置jQuery进入“无冲突”模式在jQuery被加载到页面之后。

设置jQuery的无冲突模式


   
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和$j在你的页面中,当然你也可以设置其它的别名像jq、$j

最后,如果你不想给jQuery定义别名,而且你也不担心其它js框架使用$方法,那么你只需要将$作为参数传给你的$(document).ready()函数中。这是最经常使用到的方式,如果你希望使用简洁的jQuery代码,但是不希望导致和其它js框架的冲突


   
1 <!-- Another way to put jQuery into no-conflict mode. --> 2 < script src ="prototype.js" ></ script > 3 < script src ="jquery.js" ></ script > 4 < script > 5 6 jQuery.noConflict(); 7 8 jQuery( document ).ready( function ( $ ) { 9 // You can use the locally-scoped $ in here as an alias to jQuery. 10 $( " div " ).hide(); 11 }); 12 13 // The $ variable in the global scope has the prototype.js meaning. 14 window.onload = function (){ 15 var mainDiv = $( " main " ); 16 } 17 18 </ script >

这可能是最理想的解决方式对于大部分的代码,这样你讲只需要修改少量的代码却可以实现完整的兼容性

在其他JS框架前加载jQuery

上面的代码中,jQuery是在prototype.js加载之后加载的。如果你在其它框架之前引入jQuery,你可能需要使用jQuery来调用jQuery的方法,因为$可能在其它框架中定义。这时将不需要调用jQuery.noConflict,直接将$作为jQuery(document).ready(function())的参数,就可以在该作用域内继续使用$来调用jQuery函数


   
1 <!-- Loading jQuery before other libraries. --> 2 < script src ="jquery.js" ></ script > 3 < script src ="prototype.js" ></ 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 >

   
1 < script src ="jquery.js" ></ script > 2 < script src ="prototype.js" ></ script > 3 < script > 4 5 jQuery( function ($){ 6 // Your jQuery code here, using the $ 7 }); 8 9 </ script >

转载于:https://my.oschina.net/Dispatcher/blog/420605

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值