How to pass 'this' into a setTimeout callb

2019-02-16 19:33发布

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'

8条回答
SAY GOODBYE
2楼-- · 2019-02-16 20:34

You need to store this in a separate variable:

$('.item').each(function () {
  var me = $(this);
  setTimeout(function () {
    me.fadeIn(1000);
  }, Math.floor(Math.random() * 1000));
})
查看更多
三岁会撩人
3楼-- · 2019-02-16 20:37

The trick here is to save this into a local that can be evaluated safely in the setTimeout callback

$('.item').each(function () {
  var self = this;
  setTimeout(function () {
    $(self).fadeIn(1000);
  }, Math.floor(Math.random() * 1000));
});
查看更多
登录 后发表回答