2013-09-24 41 views
0

如何设置元素的html,等待2秒,然后将html设置为其他内容?jQuery .delay不会延迟

例子:$("div").html("clicked").delay(2000).html("2 seconds have passed");

会发生什么:股利获得“2秒钟后”的蝙蝠,而不是说“点击” 2秒钟,然后显示“2秒钟过去了”。

我需要做类似的事吗,.delay(2000, function() { $("div").html("2 seconds have passed"); })

活生生的例子在这里:http://jsbin.com/UfaYusU/1/edit

谢谢!

+1

你需要把它放在队列中() –

回答

3

$ .delay用于延迟队列中的动画,而不是暂停执行。

试试这个:

setTimeout(function() { 
      // Do something after 2 seconds 
}, 2000); 
2

.delay()默认情况下只用动画功能的工作原理,你可以使用.promise()方法:

$("div").html("clicked").delay(2000).promise().done(function() { 
    $(this).html("2 seconds have passed"); 
}); 
+0

“只适用于动画功能”,并不像我所知的那样。适用于排队的所有事情 –

+0

@ A.Wolff是的,从技术上讲,这是正确的,我的意思是_by default_。 – undefined

+0

我从来没有想过在这种情况下使用.promise(),即使现在连续多次点击似乎打破它http://jsfiddle.net/fsvFj/ –

0

使用setTimeout()如果你想有一个延迟后运行一些代码.. 。

$("button").click(function(e) { 
    $("div").html("clicked"); 
    setTimeout(function() { 
    $("div").html("2 seconds have passed"); 
    }, 2000); 
}); 

Here's an updated version of your jsbin...