我正在调用一个匿名函数:
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];
}
希望你能得到一些想法。
关于JavaScript - 将参数传递给匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16632136/