Javascript 如何检查 jQuery 插件和功能是否存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5339876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check jQuery plugin and functions exists?
提问by Amr Elgarhy
I have a plugin in some pages but in some other pages I don't want it so I didn't reference its script file.
我在某些页面中有一个插件,但在其他一些页面中我不想要它,所以我没有引用它的脚本文件。
How to check if the plugin functions exist before using it.
如何在使用之前检查插件功能是否存在。
In my case I am using this plugin: and I use it like this:
就我而言,我正在使用这个插件:我像这样使用它:
$('#marquee-inner div').marquee('pointer').mouseover(function() {
$(this).trigger('stop');
}).mouseout(function() {
$(this).trigger('start');
}).mousemove(function(event) {
if ($(this).data('drag') == true) {
this.scrollLeft = $(this).data('scrollX') + ($(this).data('x') - event.clientX);
}
}).mousedown(function(event) {
$(this).data('drag', true).data('x', event.clientX).data('scrollX', this.scrollLeft);
}).mouseup(function() {
$(this).data('drag', false);
});
What I want is to make a check before calling this marquee function if it exist or not.
我想要的是在调用这个选取框函数之前检查它是否存在。
回答by Matt Ball
if ($.fn.marquee) {
// there is some jquery plugin named 'marquee' on your page
}
回答by Madan Sapkota
You can also do this. Let me take jQuery marquee example.
你也可以这样做。让我以 jQuery 选框为例。
This is good if you are using only jQuery.
如果您只使用 jQuery,这很好。
if($().marquee) {
// marquee is loaded and available
}
OR
或者
if($.fn.marquee !== undefined) {
// marquee is loaded and available
}
Similar to above but Safe when you are using other JS frameworks Mootools etc.
与上面类似,但是当您使用其他 JS 框架 Mootools 等时是安全的。
if(jQuery().marquee) {
// marquee is loaded and available
}
OR
或者
if(jQuery.fn.marquee !== undefined) {
// marquee is loaded and available
}
回答by Noyo
Slightly better:
稍微好一些:
if ($.isFunction($.fn.marquee)) {
// ...
}
Maybe a little overkill, but this will ensure that it's at least a function.
也许有点矫枉过正,但这将确保它至少是一个功能。