0

我做了一个这样的 JavaScript 计数器:

window.onload = function(){
    var target_date = new Date("Aug, 15, 2019").getTime();
}
var days, hours, minutes, seconds;
var countdown = document.getElementById("countdown");

setInterval(function (){
    var current_date = new Date().getTime();
    var seconds_left = (target_date - current_date) / 1000;

    days = parseInt(seconds_left / 86400);
    seconds_left = seconds_left % 86400;

    hours = parseInt(seconds_left / 3600);
    seconds_left = seconds_left % 3600;

    minutes = parseInt(seconds_left / 60);
    seconds = parseInt(seconds_left % 60);

    countdown.innerHTML= days + "d, " + hours + "h, " + minutes + "m, " + seconds + "s"; 
}, 1000); 

HTML:

<span id="countdown"></span>

浏览器(谷歌 Chorme)说:

Uncaught ReferenceError: target_date is not defined

即使我删除window.onload = function(){}, 仍然无法正常工作。我做错了什么?

4

3 回答 3

3

这一切都与变量作用域有关。这里 yourtarget_date是在 your 中定义的window.onload,使其成为该函数的本地函数。如果要在该函数之外使用变量,请通过将其移到函数外部来全局声明它:

var target_date; /* Declared globally. */
window.onload = function(){
    target_date = new Date("Aug, 15, 2019").getTime();
}
于 2013-10-21T07:56:13.910 回答
0

将您的第一个更改"}"为脚本的结尾

window.onload = function(){
            var target_date = new Date("Aug, 15, 2019").getTime();

        var days, hours, minutes, seconds;
        var countdown = document.getElementById("countdown");

        setInterval(function (){
            var current_date = new Date().getTime();
            var seconds_left = (target_date - current_date) / 1000;

            days = parseInt(seconds_left / 86400);
            seconds_left = seconds_left % 86400;

            hours = parseInt(seconds_left / 3600);
            seconds_left = seconds_left % 3600;

            minutes = parseInt(seconds_left / 60);
            seconds = parseInt(seconds_left % 60);

            countdown.innerHTML= days + "d, " + hours + "h, " + minutes + "m, " + seconds + "s"; 
        }, 1000); 
        }
于 2013-10-21T08:01:36.123 回答
0

只需将 window.onload 的大括号移动"}"到脚本的末尾

window.onload = function(){
    var target_date = new Date("Aug, 15, 2019").getTime();
    var days, hours, minutes, seconds;
    var countdown = document.getElementById("countdown");

    setInterval(function (){
        var current_date = new Date().getTime();
        var seconds_left = (target_date - current_date) / 1000;

        days = parseInt(seconds_left / 86400);
        seconds_left = seconds_left % 86400;
        hours = parseInt(seconds_left / 3600);
        seconds_left = seconds_left % 3600;

        minutes = parseInt(seconds_left / 60);
        seconds = parseInt(seconds_left % 60);

        countdown.innerHTML= days + "d, " + hours + "h, " + minutes + "m, " + seconds + "s"; 
    }, 1000);
}
于 2013-10-21T08:09:27.377 回答