您的位置:首页 > Web前端 > JQuery

解决jquery$命名符和其它框架的冲突问题

2014-04-22 17:48 162 查看
jquery提供了一个noConfilict的API来解决冲突。 使用方法: jQuery.noConflict():运行这个函数将变量$的控制权让渡给第一个实现它的那个库。 jQuery.noConflict(true):将$和jQuery的控制权都交还给原来的库。 第一种:
jQuery.noConflict();
// Do something with jQuery
jQuery("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';

第二种:
jQuery.noConflict();
(function($) {
$(function() {
// more code using $ as alias to jQuery
});
})(jQuery);
// other code using $ as an alias to the other library
第三种:
jQuery.noConflict()(function(){
// code using jQuery
});
// other code using $ as an alias to the other library

第四种:
var j = jQuery.noConflict();
// Do something with jQuery
j("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';

第五种:
var dom = {};
dom.query = jQuery.noConflict(true);
// Do something with the new jQuery
dom.query("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';
// Do something with another version of jQuery
jQuery("div > p").hide();

noConfilict的源码:
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}

if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}

return jQuery;
},

在jquery源码的最开头定义了:
(function(){
  var
//
_jQuery = window.jQuery,
_$ = window.$,
//
})();
为了防止$和就jQuery被覆盖而进行保存。

当deep为空的时候,“_$”覆盖“window.$”,“$”的常规功能失效,但jQuery还可以继续使用。当有新的库中重新定义“$”的时候,“jQuery”继续为jQquery的常规功能,而“$”就不是jQuery中的了,它是属于新的库的常规功能;
当deep不为空的时候,它将“_jQuery”覆盖“window.jQuery”,这样导致可能jQuery插件失效;另外方法返回的jQuery,实际上没有被覆盖。通过它完全可以移到新的一个命名空间,如dom.query = jQuery.noConflict(true); dom.query("div p").hide();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐