如何将'this'传递给setTimeout回调 [英] How to pass 'this' into a setTimeout callback

查看:99
本文介绍了如何将'this'传递给setTimeout回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

css

  .item {
display:none;
}

html

 < div> 
< div class =item> machin< / div>
< div class =item>选择< / 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()的第3个参数,因为它不适用于IE。

不建议使用 setTimeout()出于安全原因使用 eval 方法。



那么我怎样才能通过 setTimeout()






编辑



我知道这个问题已经发布了。

但是我觉得它有点规格使用每个()上下文.-
现在有人完全改变了我的问题的标题,这个标题最初类似于'setTimeout() - jQuery.each()这个对象参数'

解决方案

不要使用setTimeout,使用jQuery自己的工具。<每一个(function(){
$(this).delay(数学。) random()* 1000).fadeIn();
})

http://api.jquery.com/delay/



工作示例:http://jsfiddle.net/qENhd/


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'

解决方案

Do not use setTimeout, use jQuery own tools.

$('.item').each(function () {
   $(this).delay(Math.random() * 1000).fadeIn();
})

http://api.jquery.com/delay/

Working example: http://jsfiddle.net/qENhd/

这篇关于如何将'this'传递给setTimeout回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆