如何将'this'传递给setTimeout回调

Pie*_*NAY 9 javascript jquery scope settimeout

CSS

.item {
  display: none;
}
Run Code Online (Sandbox Code Playgroud)

HTML

<div>
  <div class="item">machin</div>
  <div class="item">chose</div>
  <div class="item">chouette</div>
  <div class="item">prout</div>
</div>
Run Code Online (Sandbox Code Playgroud)

我正在使用jQuery,我想让每个都.item出现在一个随机的小计时器之后:

JavaScript的

$('.item').each(function () {
  itm = $(this);
  setTimeout(function () {
    itm.fadeIn(1000);
  }, Math.floor(Math.random() * 1000));
})
Run Code Online (Sandbox Code Playgroud)

这里itm将始终包含最后一项,因为在所有赋值后评估函数.
我不能使用第3个参数,setTimeout()因为它不适用于IE.
这不是建议使用setTimeout()与EVAL出于安全原因的方法.

那么我如何通过访问我的对象setTimeout()?


编辑

我知道这个问题已经发布了.
但我认为它与each()上下文略有一致.
现在有人完全改变了我的问题的标题,原来就是'setTimeout() - jQuery.each()这个对象参数'

geo*_*org 15

不要使用setTimeout,使用jQuery自带的工具.

$('.item').each(function () {
   $(this).delay(Math.random() * 1000).fadeIn();
})
Run Code Online (Sandbox Code Playgroud)

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

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


xan*_*ded 13

创建/使用closure:

$('.item').each(function () {
  var that = this;

  setTimeout(function () {
    $(that).fadeIn(1000);
  }, Math.floor(Math.random() * 1000));
})
Run Code Online (Sandbox Code Playgroud)

http://jibbering.com/faq/notes/closures/

https://developer.mozilla.org/en/JavaScript/Guide/Closures