2013-05-19 47 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]; 
} 

希望你会有一些想法。

相关问题