50

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

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

就我而言,我正在使用这个插件:我像这样使用它:

$('#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);
});

我想要的是在调用这个选框函数之前检查它是否存在。

4

3 回答 3

129
if ($.fn.marquee) {
    // there is some jquery plugin named 'marquee' on your page
}
于 2011-03-17T13:46:59.827 回答
19

你也可以这样做。让我以 jQuery 选框为例。

如果您只使用 jQuery,这很好。

if($().marquee) {
    // marquee is loaded and available
}

或者

if($.fn.marquee !== undefined) {
    // marquee is loaded and available
}

与上面类似,但当您使用其他 JS 框架 Mootools 等时是安全的。

if(jQuery().marquee) {
    // marquee is loaded and available
}

或者

if(jQuery.fn.marquee !== undefined) {
    // marquee is loaded and available
}
于 2013-04-18T13:04:06.307 回答
4

稍微好一些:

if ($.isFunction($.fn.marquee)) {
    // ...
}

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

2021 年 1 月更新:

由于自jQuery.isFunction()3.3 版起已弃用,现在最简单且推荐的检查方法是:

if (typeof $.fn.marquee === "function") {
    // ...
}

请注意,这对于某些非常旧的浏览器可能还不够——有关详细信息,请参阅$.isFunction()实现

于 2013-09-03T17:44:56.197 回答