如何修复Javascript制作的实时时钟(我在网页上看不到)?

How do I fix a real-time-clock made in Javascript(I can't see it in the webpage)?

我试图按照互联网上的一些教程创建一个时钟,但我遇到了问题。时钟应该每秒更新一次并显示当前时间。需要你的帮助吗?这应该是结果:https://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock 。这是我的代码:

function startClock() {
  var currentTime = new Date();
  console.log(currentTime);

  var currentHours = currentTime.getHours();
  console.log(currentHours);

  var currentMinutes = currentTime.getMinutes();
  console.log(currentMinutes);

  var currentSeconds = currentTime.getSeconds();
  console.log(currentSeconds);

  currentMinutes = checkTime(m);

  currentSeconds = checkTime(s);

  var time = currentHours + ":" + currentMinutes + ":" + currentSeconds;

  document.getElementById("time").innerHTML = time;

  var repeatTime = setTimeout(startClock, 1000);
}

function checkTime(i) {
  if (i < 10) {
    i = "0" + i;
    return i;
  }
}

你的代码有四个问题:

  1. startClock() 函数将调用 setTimeout() 以确保再次调用它。但它最初从未被调用。因此,在末尾添加语句 startClock();,靠近 </script>.

  2. 变量m不存在。通过写 currentMinutes = checkTime(currentMinutes);.

  3. 来解决这个问题
  4. 变量s不存在。通过写 currentSeconds = checkTime(currentSeconds);.

  5. 来解决这个问题
  6. checkTime() 函数 returns nothing (undefined) 如果 i 不小于 10。因此,添加语句 else return "" + i;.

修复所有问题并运行!我确实测试了最后的结果。

检查要点CurrentTimeData.js