Javascript不会更新或显示系统时间<怎么会

Javascript will not update or display the system time< how come?

本文关键字:怎么会 时间 显示系统 更新 Javascript      更新时间:2023-09-26

这是我的javascript代码,我在Chrome中检查了它,它没有给我一个错误

window.onload = function() {
    var timeClock = function (){
        setTimeout("timeClock()", 1000);  
        var timeObj = new Date();
        var currTime = timeObj.getHours(); + " : " + timeObj.getMinutes(); + " : " + timeObj.getSeconds();
        document.getElementById("#clock-container").innerHTML = "asd";
    }
}

我正在尝试使用当前系统时间更新此div

<div id="clock-container"></div>

你有多个逻辑和其他错误。

  1. 您正在尝试注册回调,但您的setTimeout位于回调本身中。将setTimeout("timeClock()", 1000);移到回调之外。
  2. 大概您还希望将setTimeout替换为setInterval以使时钟不断更新,并且还避免在回调中调用setTimeout
  3. 也没有理由使用字符串来调用timeClock,所以改用setInterval(timeClock, 1000);,避免代码评估的邪恶。
  4. document.getElementById("#clock-container")应该是document.getElementById("clock-container").
  5. 您的currTime表达式有几个不属于它们的;,请修复它们,您可以使用此变量代替字符串。
  6. 您还可以在加载后立即调用timeClock,以避免等待第一个间隔。

工作示例:

window.onload = function() {
    var timeClock = function (){
        var timeObj = new Date();
        var currTime = timeObj.getHours() + " : " + timeObj.getMinutes() + " : " + timeObj.getSeconds();
        document.getElementById("clock-container").innerHTML = currTime;
    }
    setInterval(timeClock, 1000);
    timeClock();
}
<div id="clock-container"></div>

我不确定你想做什么,但脚本应该是

window.onload = function() {
var timeClock = function (){
    var timeObj = new Date();
    var currTime = timeObj.getHours() + " : " + timeObj.getMinutes() + " : " + timeObj.getSeconds();
    document.getElementById("clock-container").innerHTML = currTime;
    setTimeout(timeClock, 1000);  
}
timeClock();  
}