2013-05-19 122 views
2

我打電話的匿名函數:的JavaScript - 將參數傳遞給匿名函數

 closeSidebar(function() { 
      alert("function called"); 
      $(this).addClass("current"); 
      setTimeout(function(){openSidebar()}, 300); 
     }); 

$(this)不能按預期工作,我需要把它作爲參數傳遞到函數。經過一番研究後,我認爲這會起作用:

  closeSidebar(function(el) { 
       $(el).addClass("current"); 
       setTimeout(function(){openSidebar()}, 300); 
      })(this); 

但事實並非如此。如何將參數添加到匿名函數中?

jsFiddle - 點擊右邊的一個按鈕,它會動畫,然後調用上面的函數。當按鈕具有「當前」類時,它將在按鈕的左側有一個白色條,但該類不會改變。

回答

4

你也可以這樣做:

 closeSidebar(function(el) { 
      $(el).addClass("current"); 
      setTimeout(function(){openSidebar()}, 300); 
     }(this)); 

的參數需要傳遞給匿名函數本身,而不是調用。

+0

啊支架在錯誤的地方..謝謝! –

+1

這是有效的語法?在這裏,我想'closeSidebar(function(el){}(this));'最好*調用函數並將其返回給'closeSidebar'。 –

1

使用此方法添加參數:

var fn=function() { }; 
fn.apply(this,arguments); 
5

你可以參考下面的代碼,在匿名函數中傳遞參數。

var i, img; 
for(i = 0; i < 5; i++) 
{ 
    img = new Image(); 
    img.onload = function(someIndex) 
    { 
    someFunction(someIndex); 
    }(i); 
    img.src = imagePaths[i]; 
} 

希望你會有一些想法。

相關問題