2012-12-01 35 views
21

可能重複:
jQuery test for whether an object has a method?在調用之前檢查函數是否存在?

我想,如果函數調用之前就存在設置的JavaScript你能幫助我如何做到這一點,適用於該腳本

$(document).ready(function() { 
    $(".cs-text-cut").lettering('words'); 
}); 
+0

@Alexei:從這個例子來看,我認爲它完全一樣。即使不是,解決方案(使用'.isFunction')仍然是相同的,並且很容易轉移。 –

+0

@FelixKling,你說得對,確切地說是dup。以某種方式解釋它擴大(如果一個使用元素,而不是jQuery選擇器的結果)。 –

回答

65

我假設你想檢查並確保lettering存在,請試試這個:

http://api.jquery.com/jQuery.isFunction/

下面是一個例子:

if ($.isFunction($.fn.lettering)) { 
    $(".cs-text-cut").lettering('words'); 
} 
+1

+1。爲了使用'isFunction',注意條件是錯誤的 - 不應該在窗口上檢查一個。 –

+1

以下按預期方式工作: 'if($ .isFunction(window.lettering)){' 如果您有簡寫方式或更好的方式請隨時通知我,我會更新建議。 – gregwhitworth

+3

該函數實際上是在'$ .fn.lettering'中,而不是'window.lettering'。 –

6

如果這是你要測試的lettering功能,你可以這樣做這樣的;

$(document).ready(function() { 
    var items = $(".cs-text-cut"); 
    if (items.lettering) { 
     items.lettering('words'); 
    } 
}); 

或者,如果你想絕對肯定items.lettering是試圖調用之前的函數,你可以這樣做:

$(document).ready(function() { 
    var items = $(".cs-text-cut"); 
    if (typeof items.lettering === "function") { 
     items.lettering('words'); 
    } 
}); 

或者,如果你真的不控制環境,你真的不知道,如果刻字函數調用是去工作或沒有,甚至可能會引發異常,你可以把一個異常處理周圍:

$(document).ready(function() { 
    try { 
     $(".cs-text-cut").lettering('words'); 
    } catch(e) { 
     // handle an exception here if lettering doesn't exist or throws an exception 
    } 
}); 
+1

+1。合理的方式來檢查jQuery select結果的屬性。添加isFunction檢查可能很好,但不是必需的。 –

+0

絕對是我的首選方式,因爲它不依賴於額外的庫。 – cfx

12

使用此檢查functi存在。

<script> 
if (typeof function_name == 'function') { 
     //function_name is a function 
} 
else 
{ 
//do not exist 
} 
</script> 
0

typeof $({}).lettering == 'function'$.isFunction($({}).lettering)應返回一個布爾它是否的產品尚未推出與否。

相關問題