如何检查jQuery插件和函数是否存在?

Amr*_*rhy 48 javascript jquery marquee jquery-plugins

我有一些插件在一些页面,但在其他一些页面我不想要它所以我没有引用它的脚本文件.

如何在使用之前检查插件功能是否存在.

在我的情况下,我使用这个插件:我像这样使用它:

$('#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);
});
Run Code Online (Sandbox Code Playgroud)

我想要的是在调用此选取框函数之前进行检查(如果存在与否).

Mat*_*all 126

if ($.fn.marquee) {
    // there is some jquery plugin named 'marquee' on your page
}
Run Code Online (Sandbox Code Playgroud)


Mad*_*ota 18

你也可以这样做.让我以jQuery marquee为例.

如果你只使用jQuery,这很好.

if($().marquee) {
    // marquee is loaded and available
}
Run Code Online (Sandbox Code Playgroud)

要么

if($.fn.marquee !== undefined) {
    // marquee is loaded and available
}
Run Code Online (Sandbox Code Playgroud)

与上面类似,但在使用其他JS框架Mootools等时安全.

if(jQuery().marquee) {
    // marquee is loaded and available
}
Run Code Online (Sandbox Code Playgroud)

要么

if(jQuery.fn.marquee !== undefined) {
    // marquee is loaded and available
}
Run Code Online (Sandbox Code Playgroud)


Noy*_*oyo 5

稍微好一些:

if ($.isFunction($.fn.marquee)) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

也许有些矫kill过正,但这将确保它至少是一个功能。