-1
$(document).ready(function () {
counter.innerHTML = "3";
var t1 = setTimeout(function () { counter.innerHTML = "2"; }, 1000);
var t2 = setTimeout(function () { counter.innerHTML = "1"; }, 1000);
var t3 = setTimeout(function () { counter.innerHTML = null; }, 1000);
});

你好,为什么 innerHTML 在我的 setTimeout 中不起作用?有更好的倒计时理由吗?谢谢!

4

3 回答 3

3
$(document).ready(function () {
counter.innerHTML = "3";
var t1 = setTimeout(function () { counter.innerHTML = "2"; }, 1000);
var t2 = setTimeout(function () { counter.innerHTML = "1"; }, 2000);
var t3 = setTimeout(function () { counter.innerHTML = null; }, 3000);
});

尝试这个

于 2013-07-17T23:57:09.220 回答
2

您还可以使其递归,这使您可以轻松更改倒计时的数字:

ONLINE DEMO

$(document).ready(function () {

    function countDown(num) {
        if (num > 0) {
            counter.innerHTML = num.toString();
            setTimeout(function(){countDown(num-1)}, 1000);
        }
    }

    countDown(3);
});

您可以扩展它,以便在倒计时完成时使用回调函数:

ONLINE DEMO EXT.

function countDown(num, callback) {
    if (num > 0) {
        counter.innerHTML = num.toString();
        setTimeout(function(){countDown(num-1, callback)}, 1000);
    } else {
        callback()
    }
}
countDown(3, function() {alert('Done!')});
于 2013-07-18T00:05:03.137 回答
0

这里:

function createCountdown(count){
    counter.innerHTML = count ? count : null;
    if(count--){
        setTimeout(function(){createCountdown(count);}, 1000);
    }
}
createCountdown(3);

您的代码不起作用是因为所有代码都setTimeout同时触发。

于 2013-07-18T00:21:54.223 回答