Javascript 倒计时无效

Javascript countdown won't work

我正在尝试为我的网站设置 Javascript 倒计时,因此我想首先测试最佳解决方案。我现在有一个代码,但是当我打开网站时,那里什么也没有,我想我在尝试将 Javascript 实现为 html?

时可能做错了什么

我的代码:

<!DOCTYPE html>


<html>

<head>

    <title>Home Test Countdown</title>

    <script LANGUAGE="Javascript">

    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);

</script>

</head>

<body>

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

</body>

</html>

因为你在头部有脚本,当执行 var countdown = document.getElementById("countdown"); 时,元素不存在于 dom 中,所以 countdown 将为空,这将导致错误 Uncaught TypeError: Cannot set property 'innerHTML' of null 在行 countdown.innerHTML = '...'.

一种可能的解决方案是将您的代码移动到 window 加载事件处理程序

window.addEventListener('load', 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);
})

演示:Fiddle

另一种是在<span id="countdown"></span>

之后将您的脚本移动到页面底部

此代码有效,您需要在 HTML 元素之后添加代码(在关闭正文标记之前添加 javascript 代码)

或尝试在 window.onload 中添加您的代码,例如

window.onload = function(){
   // your timer code goes here
};

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);
<span id="countdown"></span>

您还添加了标签 jquery,这样您就可以在 $.ready() 中添加您的代码,例如,

$(function(){
   // your code here
});

脚本需要跨度倒计时对象

之后