开发者

jQuery setTimeout - not working when using to update data

I have a list of thumbnails. When I click on a thumbnail, I want the image to load after half a second. Here's my code:

$('ul#thumbs li img').click(function() 开发者_运维百科{

    setTimeout(function() {
        $('img#image').attr("src", $(this).attr("src").replace("_thumb", ""));
    }, 500);

});

When I click on one of the thumbs, nothing happens. If I remove the setTimeout function, and just have the image load immediately, it works fine.

Anybody know why the event wouldn't fire?


this isn't what you think it is. When you use setTimeout, this is no longer a reference to the current element when the function gets executed.

You'll need to make sure you are keeping track of the proper element, like so:

$('ul#thumbs li img').click(function() {
    var thumbImg = this;
    setTimeout(function() {
        $('img#image').attr("src", $(thumbImg).attr("src").replace("_thumb", ""));
    }, 500);

});


The problem is the scope of this in the timeout function try this:

$('ul#thumbs li img').click(function() {
    var self = $(this);
    setTimeout(function() {
        $('img#image').attr("src", self.attr("src").replace("_thumb", ""));
    }, 500);

});

Or even better this:

$('ul#thumbs li img').click(function() {
    var src = $(this).attr("src").replace("_thumb", "");
    setTimeout(function() {
        $('img#image').attr("src", src);
    }, 500);

});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜