开发者

jQuery does not show content with setTimeout

I am trying to get a content appear after sometime after making an ajax request with jQuery but I am getting some trouble with it.

Here is the code:

$.ajax({
            url: 'content.php',
            data: '&go=' + tab,
            success: function(d开发者_如何学运维ata) {
                setTimeout("pencil()",3250);
                setTimeout('$("#content").html(data).fadeIn()',5000);
            }
        });

The problem is that the "content" is not loaded this way after 5 seconds. However if I put it without the setTimeout it appears right away - but that way it smashes the animation.

How can I fix this?

Thank you.


You are using the variable data in the string passed to setTimeout, but that variable will no longer exist when the string is executed.

You can fix this by using a function object instead of a string:

setTimeout(function() { 
    $("#content").html(data).fadeIn() 
}, 5000);

This works because the value of data is held in a closure.


The problem is probably putting jquery code in the setTimeout in string input. Try this:

setTimeout(function(){$("#content").html(data).fadeIn()},5000);

I think this should work. The problem with your previous approach is setTimeout cannot run functions with inputs for example if you wrote "pencil(data);" it wouldn't work either.


You need to wrap your jQuery call in a function

$.ajax({
    url: 'content.php',
    data: '&go=' + tab,
    success: function (data) {
        setTimeout(pencil, 3250); //pass in a function reference preferably. 
        setTimeout(function(){$("#content").html(data).fadeIn()}, 5000); //wrap it in a function
    }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜