document.getElementById根本不起作用

时间:2017-06-30 07:16:26

标签: javascript google-chrome-app

我是一个巨大的北欧神话爱好者,我正在尝试制作一个Ragnarok倒计时Chrome应用。代码在一个编辑网站上工作正常,即使我把它放在这篇文章中,但当我尝试将其作为应用程序打开时,显示时钟的document.getElementById无论做什么都不做做,我做了一切。这是代码:



<!DOCTYPE HTML>
<html>
<head>
<style>
p {
  text-align: center;
  font-size: 60px;
}
body {
    color:white;
    background-color:gray;
</style>
    </head>
<body>

<p id="demo"></p>
<script>
 window.onload = (function () {// Set the date we're counting down to
var countDownDate = new Date("Jan 1, 2099 12:00:00").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

    // Get todays date and time
    var now = new Date().getTime();
    
    // Find the distance between now an the count down date
    var distance = countDownDate - now;
    
    // Time calculations for days, hours, minutes and seconds
    var years = Math.floor(distance / (1000 * 60 * 60 * 24 * 365));
    var days = Math.floor((distance % (1000 * 60 * 60 * 24 * 365)) / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    
    // Output the result in an element with id="demo"
    document.getElementById("demo").innerHTML = years + "y" + days + "d " + hours + "h "
    + minutes + "m " + seconds + "s ";
    
    // If the count down is over, write some text 
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "Prepare for Ragnarok";
    }
}, 1000);});
</script>


</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

评论中的建议是正确的。将标签内的所有Javascript移动到单独的文件,例如script.js。然后将脚本标记替换为引用该文件的脚本标记:

<script src="script.js"></script>