开发者

jQuery why $(this) doesn't work in a setTimeout method?

I have this jQuery code:

$('#loadingDiv开发者_开发技巧2')
.css('visibility','hidden')  // hide it initially
.ajaxStart(function() {
    $(this).css('visibility','visible');
    $("#bbdata").empty();
})
.ajaxStop(function() {
    $(this).css('visibility','hidden');// works here 
setTimeout(function(){
    $(this).css('visibility','hidden');// doesn't work here
    }, 100);
});

why $(this) doesn't work in a setTimeout method?


It doesn't work because this is a different context at that point (window), you have a few optons though, store a reference to what you want to deal with, like this:

.ajaxStop(function() {
  var $this = $(this);
  setTimeout(function(){
    $this.css('visibility','hidden');
  }, 100);
});

Or use $.proxy() for to set the context in that anonymous function, like this:

.ajaxStop(function() {
  setTimeout($.proxy(function(){
    $(this).css('visibility','hidden');
  }, this), 100);
});

In the first solution we store a reference to what we want to deal with, in the second we're actually setting that this is when that function runs...otherwise it'll be window.


There's an issue with this in setTimout, it's clarified in the docs.
But that's not big deal, you can always use var that = this; trick.


setTimeout runs in the global context, where this refers to the window object.

Try storing a reference to this instead:

.ajaxStop(function() {
    var me = this;
    setTimeout(function(){
        $(me).css('visibility','hidden');
    }, 100);
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜