如何通过“这个”?进入 setTimeout 回调
css
.item {
display: none;
}
html
<div>
<div class="item">machin</div>
<div class="item">chose</div>
<div class="item">chouette</div>
<div class="item">prout</div>
</div>
我正在使用 jQuery,我想让每个 .item
出现在一个随机的小计时器之后,例如:
javascript
$('.item').each(function () {
itm = $(this);
setTimeout(function () {
itm.fadeIn(1000);
}, Math.floor(Math.random() * 1000));
})
这里 itm
将始终包含最后一项,因为该函数在所有赋值之后进行评估。
我无法使用 setTimeout()
的第三个参数,因为它在 IE 上不起作用。
出于安全原因,不建议将 setTimeout()
与 eval 方法一起使用。
那么如何通过 setTimeout() 访问我的对象呢?
编辑
我知道这个问题已经发布。
但我认为它与 each()
上下文略有具体。
现在有人完全改变了我的问题的标题,最初是这样的“setTimeout() - jQuery.each() 这个对象参数”
css
.item {
display: none;
}
html
<div>
<div class="item">machin</div>
<div class="item">chose</div>
<div class="item">chouette</div>
<div class="item">prout</div>
</div>
I'm using jQuery and I'd like to make each .item
appearing after a random little timer like:
javascript
$('.item').each(function () {
itm = $(this);
setTimeout(function () {
itm.fadeIn(1000);
}, Math.floor(Math.random() * 1000));
})
Here itm
will always contain the last item because the function is evaluated after all assignments.
I can't use the 3rd parameter of setTimeout()
because it will not work on IE.
It's not advised to use setTimeout()
with the eval method for security reasons.
So how can I access to my object through setTimeout()
?
Edit
I know that this question have already been posted.
But I though that it were slightly specific with the each()
context.
Now someone have entirely changed the title of my question that was originally something like 'setTimeout() - jQuery.each() this object parameter'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
不要使用setTimeout,使用jQuery自带的工具。
http://api.jquery.com/delay/
工作示例:http://jsfiddle.net/qENhd/
Do not use setTimeout, use jQuery own tools.
http://api.jquery.com/delay/
Working example: http://jsfiddle.net/qENhd/
创建/使用
闭包
:http://jibbering.com/faq/notes /closures/
https://developer.mozilla.org/en/JavaScript/Guide/Closures
Create/Utilize a
closure
:http://jibbering.com/faq/notes/closures/
https://developer.mozilla.org/en/JavaScript/Guide/Closures
在
setTimeout
执行之前,each
循环已经完成执行,它不会等待。同样在setTimeout
函数中this
不会引用 DOM 元素。尝试这样的事情。
你也可以尝试这样的事情。
Before
setTimeout
executeseach
loop would have finished executing, it will not wait. Also insidesetTimeout
functionthis
will not refer to the DOM element.Try something like this.
You can also try something like this.
您需要将
this
存储在单独的变量中:You need to store
this
in a separate variable:这里的技巧是将
this
保存到本地,可以在setTimeout
回调中安全地进行评估The trick here is to save
this
into a local that can be evaluated safely in thesetTimeout
callback试试这个:
Try this:
尝试一下这个:
我无法解释它为什么有效,但我认为这是对 setTimeout 中另一个“this”的引用。
http://jsfiddle.net/Pdrfz/
Try this insteed:
I can't explain why it works, but i think this is a reference to another "this" in your setTimeout.
http://jsfiddle.net/Pdrfz/
试试这个:
Try this: