如何修复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;
}
}
你的代码有四个问题:
startClock()
函数将调用 setTimeout()
以确保再次调用它。但它最初从未被调用。因此,在末尾添加语句 startClock();
,靠近 </script>
.
变量m
不存在。通过写 currentMinutes = checkTime(currentMinutes);
.
来解决这个问题
变量s
不存在。通过写 currentSeconds = checkTime(currentSeconds);
.
来解决这个问题
checkTime()
函数 returns nothing (undefined
) 如果 i
不小于 10。因此,添加语句 else return "" + i;
.
修复所有问题并运行!我确实测试了最后的结果。
我试图按照互联网上的一些教程创建一个时钟,但我遇到了问题。时钟应该每秒更新一次并显示当前时间。需要你的帮助吗?这应该是结果: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;
}
}
你的代码有四个问题:
startClock()
函数将调用setTimeout()
以确保再次调用它。但它最初从未被调用。因此,在末尾添加语句startClock();
,靠近</script>
.变量
m
不存在。通过写currentMinutes = checkTime(currentMinutes);
. 来解决这个问题
变量
s
不存在。通过写currentSeconds = checkTime(currentSeconds);
. 来解决这个问题
checkTime()
函数 returns nothing (undefined
) 如果i
不小于 10。因此,添加语句else return "" + i;
.
修复所有问题并运行!我确实测试了最后的结果。