2011-10-01 122 views
0

我有一個以下場景,我必須動態調用一個jQuery對象上的函數。代碼如下所示:jquery動態調用函數

$('div[class]').each(function(){ 
    var class=$(this).attr('class'); 

    // I want to now check if that function with the name of class exists for jquery 
    // object. I need help here. 
    // if that function exists, i need to apply that function to the enumerated object. 
}); 

我想現在檢查該類的名稱是否存在用於jQuery對象的函數。我需要幫助。如果該函數存在,我需要將該函數應用於枚舉對象。

+0

:如果函數是一個jQuery方法,然後嘗試我無法在這裏清楚地看到你的用例。你想達到什麼目的?解釋一下,如果我這樣做,那麼這應該發生!如果這個元素有類'abc',我希望函數'abc'被執行,等等...... – Shef

+0

是的,如果元素具有類abc,那麼我希望在該元素上執行abc,如果該函數存在。 – emphaticsunshine

+1

存在於全局命名空間中jQuery的'jQuery.fn.function_here'中?另外,你確定你的元素只有一個類嗎? – Shef

回答

2

我寫這篇文章我的頭頂部,因此它可能無法正常工作,但嘗試:

if(jQuery.isFunction(jQuery[class])) 
    jQuery[class](this); 

編輯:

if(jQuery.isFunction(jQuery.fn[class])) { 
    jQuery.fn[class](this); 
    jQuery(this)[class](); // alternative call syntax 
} 
+0

我認爲這是非常接近,我一直在尋找。謝謝 – emphaticsunshine

0

使用$.isFunction(func)來確定func是否爲函數。

+0

我想我可以只傳遞該對象的屬性在該函數。它接受變量嗎?例如: var class ='accordion'; $ .isFunction(class); 這項工作? – emphaticsunshine