【发布时间】:2012-01-04 23:12:18
【问题描述】:
文档说您可以像这样使用 $.noConflict():
jQuery.noConflict();
(function($) {
$(function() {
// more code using $ as alias to jQuery
});
})(jQuery);
// other code using $ as an alias to the other library
它还声明调用它会返回一个 jQuery 对象的实例,所以我可以这样做:
jQuery.noConflict()(function(){
// code using jQuery
});
// other code using $ as an alias to the other library
但是,这种组合有效吗?
(function($) {
$(function() {
// more code using $ as alias to jQuery
});
})(jQuery.noConflict());
// other code using $ as an alias to the other library
如果是这样,有理由不这样做吗?还有(如果可行的话),为什么不总是使用这种方法来保证在我们的闭包内部,$ == jQuery?
【问题讨论】:
-
我看到的唯一缺点是,如果您有多个这样的块,您将不必要地多次调用
jQuery.noConflict()。诚然,这并不是一个非常显着的缺点。 -
@Wiseguy 是的,我认为你会在第一次关闭时这样做,否则有点浪费。
-
那么你必须跟踪哪个块是第一个加载的。如果您稍后在前一个第一个文件之上添加一个块/包含一个 .js 文件怎么办?我最好在最顶部使用
<script>jQuery.noConflict();</script>,并在整个过程中使用(function($){})(jQuery)。我猜基本上归结为个人喜好。