繁体   English   中英

JavaScript - 将参数传递给匿名函数

[英]JavaScript - Passing Arguments to Anonymous Functions

我正在调用一个匿名函数:

        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 - 单击右侧的按钮,它会动画然后调用上面的函数。 当按钮具有“当前”类时,按钮左侧将有一个白色条,但类永远不会改变。

您可以参考下面的代码,在匿名函数中传递参数。

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

希望你能得到一些想法。

你也可以这样做:

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

参数需要传递给匿名函数本身,而不是调用者。

使用此方法添加参数:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM