JavaScript时钟。 预期结果:显示日期和时间。 问题:不显示
[在左上角显示时钟/时间] [1]
此代码应将时间插入ID值为“时间”的div中。我怀疑有一个setTimeout函数没有被正确利用。我的问题是时间没有显示。 我在这里错过了一些东西,因为时间不显示。请帮我修复它。
<script>
var dayArray= ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var monthArray= ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
function getTime() {
var today = newDate();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var d = dayArray[today.getDay()];
var mo = monthArray[today.getMonth()];
var y = today.getFullYear();
var mm = correctDigit(m);
var ss = correctDigit(s);
document.getElementById('time')
.innerHTML = "<br><h1 class='large'>"+h+":"+mm+":"+ss+"</h1> <span class='dark'>"+d+",</span> <span class='dark'>"+mo+"</span> <span class='dark'>"+y+"</span>";
var t = setTimeout (function() {
getTime();
}, 1000);
function correctDigit(i){
if(i < 10){
i = "0" + i;
}
return i;
};
};
</script>
</head>
<body onload="getTime()" class="color-4">
<section>
<div class='time color-0' id="time"></div>
答案 0 :(得分:1)
我已通过以下方式解决了您的紧迫问题
body
的{{1}}属性以调用要运行的函数onload
getTime()
中的new
和Date
之间放置一个空格。现在将日历添加到DOM并每秒更新一次,但是您的日历逻辑似乎仍然存在一些问题。 (提示:分钟和秒数少于10时有效;由于这不是您问题的主要部分,因此我将其留给您自己解决的练习-这就是您的学习方式!)< / p>
var today = newDate()
答案 1 :(得分:0)
这是一个有效的工作示例,但有一些明显的区别。
setTimeout
放在了getTime
函数之外setInterval
代替了setTimeout
String.padStart()
填写了缺失的0 对于setInterval
,您可以将其分配给变量,如果要停止时钟,请调用clearInterval(variableName)
。将setTimeout
分配给变量不会为您做任何事情。
如果您想使用momentJS轻松实现,请查看底部的演示
var dayArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
monthArray = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
function getTime() {
var today = new Date(),
h = today.getHours(),
m = today.getMinutes().toString().padStart(2, '0'),
s = today.getSeconds().toString().padStart(2, '0'),
d = dayArray[today.getDay()],
mo = monthArray[today.getMonth()],
y = today.getFullYear();
document.getElementById('time').innerHTML =
`<br>` +
`<h1 class='large'>${h}:${m}:${s}</h1> ` +
`<span class='dark'>${d},</span> ` +
`<span class='dark'>${mo}</span> ` +
`<span class='dark'>${y}</span>`;
};
setInterval (function() {
getTime();
}, 1000);
<div id="time"><div>
function getTime() {
var today = moment(),
time = today.format('HH:mm:ss'),
date = today.format('dddd, MMMM, YYYY');
document.getElementById('time').innerHTML =
`<br>` +
`<h1 class='large'>${time}</h1>` +
`<span class='dark'>${date}</span>`
};
setInterval (function() {
getTime();
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<div id="time"></div>