2011-03-17 31 views
43

我在一些頁面中有一個插件,但在其他一些頁面中,我不需要它,所以我沒有引用它的腳本文件。如何檢查jQuery插件和函數是否存在?

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

在我來說,我使用這個插件:我用它是這樣的:

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

我要的是,如果它存在,或者不調用此函數字幕之前進行檢查。

+1

可能的重複[如何檢查是否加載了jQuery插件?](http://stackoverflow.com/questions/400916/how-can-i-check-if-a-jquery-plugin-is-加載) – toxalot 2013-11-23 06:29:18

+0

[詳細文章檢查jQuery或jQuery插件是否加載](http://conceptf1.blogspot.com/2013/11/jquery-library-loaded-or-not-validation.html) – 2013-12-10 17:24:15

回答

115
if ($.fn.marquee) { 
    // there is some jquery plugin named 'marquee' on your page 
} 
+1

這麼簡單,我確認它有效,謝謝。 – jackJoe 2012-10-12 09:10:51

+0

[詳細文章檢查jQuery或jQuery插件是否加載](http://conceptf1.blogspot.com/2013/11/jquery-library-loaded-or-not-validation.html) – 2013-12-10 17:24:37

+0

純JS解決方案?沒有$符號? – quarky 2017-08-04 09:18:51

17

您也可以這樣做。讓我以jQuery選框爲例。

如果您僅使用jQuery,這很好。

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

OR

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

以上,但安全類似的,當你使用的是其他js框架Mootools的等

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

OR

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

這將更好地使用!==「undefined」,因爲!==和===直接比較對象的字符串類型。所以基本上你比較的是字符串類型,我知道是工作,但也許會更加「正確」使用引號...... – ncubica 2013-06-19 17:33:52

4

稍微好一點:

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

也許有點矯枉過正,但這將確保它至少是一個函數。