2012-04-02 76 views
5

我想知道用jQuery製作這個簡單(也許是愚蠢的)事情的方法。傳遞函數作爲參數,然後在jQuery函數中執行它

我有這樣的功能:

function setSomething() { 
    make some stuff; 
} 

,然後另一個功能是這樣的:

generalFunction(par1, par2, par3) { 
    do other stuff; 
    execute function called in par3;  
} 

好吧,如果我寫這樣的事情它不工作:

c=setSomething(); 
generalFunction(a, b, c); 

那麼,如何調用一個函數作爲另一個函數的參數,然後在裏面執行呢?

我希望我已經夠清楚了。

任何幫助將不勝感激。

非常感謝您的關注。

回答

11

如果省略括號,則可以在「generalFunction」函數中將該參數作爲函數調用。

setSomething(){ 
    // do other stuff 
} 

generalFunction(par1, par2, par3) { 
    // do stuff... 

    // you can call the argument as if it where a function (because it is !) 
    par3(); 
} 

generalFunction(a, b, setSomething); 
+2

+1 。注意同樣的事情適用於使用'c'的問題中的代碼,那就是說'c = setSomething; generalFunction(a,b,c);'(但是當然,正如你已經證明你不需要''c''來使它工作)。 – nnnnnn 2012-04-02 10:44:54

+0

是啊!括號!乾淨簡單! :D謝謝你的幫助!如果你願意,你可以爲我的問題投票。 – bobighorus 2012-04-02 10:51:26

0

這裏是爲那些誰想要一個參數傳遞到傳遞作爲一個回調函數又如:

$(document).ready(function() { 
    main(); 
}); 

function main() { 
    alert('This is the main function'); 
    firstCallBack(1, 2, 3, secondCallBack); 
}; 

function firstCallBack(first, second, third, fourth) { 
    alert('1st call back.'); 
    var dataToPass = first + ' | ' + second; 
    fourth(dataToPass); 
}; 

function secondCallBack(data) { 
    alert('2nd call back - Here is the data: ' + data) 
}; 

這裏是的jsfiddle鏈接:https://fiddle.jshell.net/8npxzycm/