Javascript For 循环闭包...我似乎无法理解这个问题
我怎样才能完成这项工作?
// Phrases
var phrases = new Array();
phrases[0] = 'Phrase 1';
phrases[1] = 'Phrase 2';
phrases[2] = 'Phrase 3';
for (var i = 0; i < phrases.length; i++) {
var content = phrases[i];
$('#phrase').html(content).slideDown('slow').delay(1000).fadeOut('slow');
};
这是 HTML:
<p id="phrase"></p>
将 content 变量传递到 html() 函数中我注意到 content 始终等于数组中的最后一个短语,并且循环运行幻灯片/延迟/淡入淡出功能 3 次。
我知道这与 for 循环内的闭包有关,并且我看过无数的例子,但我就是无法理解它。有人可以向我解决并解释这个问题吗?
编辑:抱歉之前不清楚,我已经编辑了这个问题以包含有问题的 HTML 和数组。
功能:不同的短语保存在phrases[]数组中,我想将短语插入到
元素中,然后向下滑动该元素,将其在屏幕上停留一秒钟,然后淡出。然后我想继续处理 phrases[] 数组中的下一个短语并执行相同的功能。
Possible Duplicate:
Javascript closure inside loops - simple practical example
How can I make this work?
// Phrases
var phrases = new Array();
phrases[0] = 'Phrase 1';
phrases[1] = 'Phrase 2';
phrases[2] = 'Phrase 3';
for (var i = 0; i < phrases.length; i++) {
var content = phrases[i];
$('#phrase').html(content).slideDown('slow').delay(1000).fadeOut('slow');
};
Here's the HTML:
<p id="phrase"></p>
Passing the content variable into the html() function I noticed that content is always equal to the last phrase in the array, and the loop runs the slide / delay / fade functions 3 times.
I know that this is something to do with closures inside a for loop and I've looked at countless examples, but I just can't get my head around it. Can someone solve and explain this one to me please?
EDIT: Apologies for being unclear before, I have edited this question to include the HTML and the array in question.
Functionality: Different phrases are held in the phrases[] array, I would like to insert the phrase into the <p>
element, then slide that element down, leave it on screen for a second, then fade it out. Then I would like to move on to the next phrase in the phrases[] array and perform the same functions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您实际上并没有闭包问题,它只是在每次迭代时将
innerHTML
设置为content
,这没有考虑到需要的效果首先完成。jsFiddle。
You don't actually have an issue with closures, it is just setting the
innerHTML
tocontent
on every iteration, which doesn't take into account the effects which need to be completed first.jsFiddle.