开发者

How can I pass a variable into jQuery timeout

开发者 https://www.devze.com 2022-12-27 11:58 出处:网络
I\'m seriously struggling today. I need to pass a variable, or even better an object, into a timeOut as such 开发者_运维技巧(example) :

I'm seriously struggling today.

I need to pass a variable, or even better an object, into a timeOut as such 开发者_运维技巧(example) :

$('.x').each(function() 
{
  setTimeout(function()
  {
    alert ($(this).attr('id'))
  },10000);
});

Obviously what happens is that the timeOut doesn't have reference to the original $(this)

Help ?


this is context sensitive (and is different in a_jQuery_object.each than it is in window.setTimeout, but its reference can be copied to a different variable that is not context sensitive. It is conventional to use that for this purpose.

$('.x').each(function() {
    var that = this; 
    setTimeout(function() { 
        alert ($(that).attr('id'))
    },10000); 
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号