【发布时间】:2017-04-10 02:56:00
【问题描述】:
我自学 JavaScript 并尝试每天编写一些代码。我目前正在尝试构建一个简单的时钟,但我似乎无法让我的 setInterval 工作。我试过将它定位在不同的地方,但我认为它属于“时间”功能,所以应该在之后定位。我想知道它是否与我调用函数的方式有关。我还不完全清楚何时通过哪种方法调用。我们将不胜感激。
var dayTime = function() {
// Create a new instance of the Date contructor function.
var date = new Date();
var today = function() {
// Create an array of weekday names
var dayArray = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
// Extract the day. Will return a numeric representation.
var dayIndex = date.getDay();
// Step 4: Use weekday names array with weekday numeric to display text version of weekday.
var today = dayArray[dayIndex];
// Step 5: Place results into span on webpage
var x = document.getElementById("day").innerHTML = today;
}()
var time = function() {
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
// Set am or pm
var amPm = hours < 12 ? "am" : "pm";
// Set to 12 hour time format
hours = hours > 12 ? hours - 12 : hours;
// Convert midnight until 1am to 12
hours = (hours == 0) ? 12 : hours;
var y = document.getElementById("time").innerHTML = "Current time is " + hours + ":" + minutes + ":" + seconds + " " + amPm;
}()
setInterval(time, 1000);
}
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body onload="dayTime();">
<h1>Simple Date Exercise</h1>
<p>Today is <span id="day"></span>
</p>
<p id="time">00:00</p>
</body>
</html>
【问题讨论】:
-
time未定义,因为您正在立即调用该函数。