使用 setTimeout 将正确的项目传递给其他函数时出现问题
我的问题是:
var slide;
$$('#slides li').each(function(i, n) {
slide = i;
setTimeout("initiateSlide()",n * 500)
});
function initiateSlide(){
i = slide;
alert(i); // pretty much alerts the last one 5 times
}
我希望 initiateSlide()
使用 5 张不同的幻灯片,但我只获得最后一张幻灯片 5 次。
Here's my problem:
var slide;
$('#slides li').each(function(i, n) {
slide = i;
setTimeout("initiateSlide()",n * 500)
});
function initiateSlide(){
i = slide;
alert(i); // pretty much alerts the last one 5 times
}
I expect to initiateSlide()
with 5 different slides, instead I only get the last one 5 times.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的问题是,您在 initiateSlide() 函数中引用的全局变量(幻灯片)在函数运行时设置为最后一个变量。您可能想使用闭包来维护变量的状态。像这样:
注意 - 这也完全消除了对全局的需要
Your problem is that the global variable (slide) that you are referencing in the initiateSlide() function is set to the last one by the time the function runs. You probably want to use closures to maintain the state of the variable. Like this:
Note - This also removes the need for the global entirely
我建议您摆脱全局变量,并将循环中的每张幻灯片作为参数传递给
initiateSlide
函数:在您的示例中,
each
循环在任何 < code>setTimeout 回调已执行,您的initiateSlide
函数正在使用最后一个迭代元素调用。I recommend you to get rid of the global variables and pass each slide within the loop as an argument to your
initiateSlide
function:In your example, the
each
loop ended before anysetTimeout
callback was executed, yourinitiateSlide
function was being invoked using the last iterated element.