魔法功能呢?
要谈论@Bradley Foster 的回答,多次调用setTimeout
是不可靠的。setTimeout
如果您的浏览器滞后,它将停止,因此有四种不同的顺序,您不确定顺序是否正确。setTimeout
正如我展示的那样嵌套更好。
$('#button').click(function() {
var seconds = 5, // Declare some variables for reuse
el = $('#some_link')
el.text(seconds) // Put it a five!
// Name your function so that you can call it later
setTimeout(function countdown() {
// Your countdown is already at 5, so decrement it
// Remember that you've already waited for 1000ms before reaching this line the first time
seconds--
el.text(seconds) // Set the new time left
// If the countdown is not over, recall this function after 1000ms
if (seconds > 0) {
setTimeout(countdown, 1000)
}
// If it is over, display the link
// Note that js will stop there and not try to call itself another time as it would with setInterval()
else {
el.html('<a href="link">Download</a>')
}
}, 1000)
})
顺便说一句,在你的问题中,当你在做的时候$(function() {...
,你实际上在做$(document).ready(function() {...
。我想这不是你想要的:)
Jsfiddle在这里:http: //jsfiddle.net/Ralt/kTbcm/