2013-06-01 52 views
1

我有這樣的功能:使用Javascript - 參數傳遞給非匿名函數

$("#btn").click(function(e,someOtherArguments) 
    { //some code 
    e.stopPropagation();}); 

它的工作原理,但如果我有命名的功能,我不能使用e,因爲它是不確定的。

var namedFunction= function(e,someOtherArguments) 
{ 
//some code 
    e.stopPropagation(); 
} 
$("#btn").click(namedFunction(e,someOtherArguments)); 

我想因爲有幾個按鈕,用它來使用這個namedFunction

回答

5

或者:

$("#btn").click(namedFunction); 

或者:

$("#btn").click(function(e,someOtherArguments){ 

    namedFunction(e, someOtherArguments); 

}); 
+3

+1。除此之外,@impeRAtoR,如果你說'$(「#btn」)。click(anyFunction)'jQuery將會調用'anyFunction()'它帶有_wants_要傳遞的參數的數量,而不是你可能或者可能沒有聲明'anyFunction()'來接受。 (事實上​​,在JS中,函數不需要顯式聲明命名參數,因爲它可以通過'arguments'對象訪問它們。) – nnnnnn

0

您可以直接調用該函數在點擊事件

$("#btn").click(function(e,someOtherArguments){ 
    namedFunction(e, someOtherArguments); 

}); 
0

您可以使用apply像這樣:

$("#btn").click(function(e,someOtherArguments){ 
    namedFunction.apply(this, arguments); 
}); 
相關問題