所以我需要这个函数用当前日期和时间更新每一秒。此外,如果分钟或秒小于10,我需要在前面添加0。继承我的代码,不知道我做错了什么,我对我的代码非常有信心。有什么建议吗?
<script>
"use strict"
// updates digital clock every second
var tick = setInterval(digitalClock, 1000);
//digital clock function
function digitalClock() {
var currentTime();
var dateObject = new Date();
var hour = dateObject.getHours();
var minute = dateObject.getMinutes();
var second = dateObject.getSeconds();
if (minute < 0) {
minute = "0" + minute;
}
if (second < 0) {
second = "0" + second;
}
currentTime = hour + ":" + minute + ":" + second;
document.getElementById('time').innerHTML = currentTime;
}
</script>
我被告知innerHTML不会在我说的地方工作,但我不明白为什么不
答案 0 :(得分:1)
在()
之后移除currentTime
,您还需要检查minute
和second
是否小于10
,而不是0
< / p>
<p id='time'></p>
<script>
function digitalClock() {
var dateObject = new Date();
var parts = {
hours: dateObject.getHours(),
minutes: dateObject.getMinutes(),
seconds: dateObject.getSeconds(),
month: dateObject.getUTCMonth() + 1,// +1 because the month starts from 0
day: dateObject.getUTCDate(),
year: dateObject.getUTCFullYear()
};
if (parts.minutes < 10) {
parts.minutes = "0" + parts.minutes;
}
if (parts.seconds < 10) {
parts.seconds = "0" + parts.seconds;
}
document.getElementById('time').innerHTML = `${parts.month}/${parts.day}/${parts.year} ${parts.hours}:${ parts.minutes}:${parts.seconds}`;
}
var tick = setInterval(digitalClock, 1000);
</script>
<强>已更新强>
这是纯粹的JavaScript
。但如果您需要多次处理时间和日期,我建议您使用momentJs
答案 1 :(得分:0)
条件应小于10并将var定义为var currentTime;而不是var currentTime();
<script>
"use strict"
// updates digital clock every second
var tick = setInterval(digitalClock, 1000);
//digital clock function
function digitalClock() {
var currentTime;
var dateObject = new Date();
var hour = dateObject.getHours();
var minute = dateObject.getMinutes();
var second = dateObject.getSeconds();
if (minute < 10) {
minute = "0" + minute;
}
if (second < 10) {
second = "0" + second;
}
currentTime = hour + ":" + minute + ":" + second;
document.getElementById('time').innerHTML = currentTime;
}
</script>