如何阻止两个jquery库彼此冲突? [英] How do I stop the two jquery libraries from conflicting with each other?
问题描述
我的页面包含了几张幻灯片,其功能与js / jquery-1.5.2.min.js完全一致。
我最近在网页(www.ug-mart.com)上推出了使用Google CDN的顶级横幅广告,但顶级横幅广告无效。我必须删除js / jquery-1.5.2.min.js才能使顶级横幅工作。
删除了js / jquery-1.5.2.min.js现在所有最初运行良好的东西现在都不起作用。只有顶级横幅才起作用。这似乎是我不能有两个和js / jquery-1.5.2.min.js在同一页上。
有没有办法停止两个jQuery库从冲突和协作?
期待您的回复。
SirBT
$ b $你可以安全地使用jQuery和其他库一起使用
.noConflict()
。通常,这是使用 $
函数名称的冲突。
我更喜欢在closure方法中使用jquery:
(函数($){
//我可以在这里安全地使用$
}(jQuery));
另外,如果您使用的是多个版本的jQuery,那么不要。只需下载最新的并使用它。它仍应该迎合一些旧的API。
继承人示例代码,以显示其工作原理:
//让我们劫持$
$ =(function(){
return {
libName:使用$
}
}());
//为我们创建一个闭包使用$
(function($){
//我们现在可以在这个闭包中安全地使用$
'('body')。text('hello world!in body!');
//让我们在这里检查$$
console.log('在这里,$是jQuery:',$);
}(jQuery));
//让我们在这里检查$
console.log('out here,$is:',$);
My page, that contains a couple of slides functioned perfectly with just js/jquery-1.5.2.min.js.
I recently introduced a top banner to my webpage (www.ug-mart.com) with googles CDN , but the top banner didnt work. I have had to remove js/jquery-1.5.2.min.js for the top banner to work.
Having removed js/jquery-1.5.2.min.js everything that initially worked well now doesn't work. Only the top banner works. It seems like i cant have both and js/jquery-1.5.2.min.js on the same page.
Is there a way to stop the the two jquery libraries from conflicting, and collaborate?
Looking forward to your reply.
SirBT
you can safely use jQuery along with other libraries using .noConflict()
. usually, it's a conflict of the use of the $
function name.
i prefer doing jquery in the "closure" method:
(function($){
//i can use "$" safely in here
}(jQuery));
also, if you are using multiple versions of jQuery, then don't. just download the latest and use it. it should still cater some of the old API.
heres a sample code to show how this works:
//lets hijack the "$"
$ = (function() {
return {
libName: "some other library using $"
}
}());
//create a closure for us to use "$"
(function($) {
//we can now use the $ safely in this closure
$('body').text('hello world! in the body!');
//let's check "$" in here
console.log('in here, "$" is jQuery:',$);
}(jQuery));
//let's check "$" out here
console.log('out here, "$" is:', $);
这篇关于如何阻止两个jquery库彼此冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!