我有一项工作,我们必须通过js文件中的函数以12小时格式插入时间。我已经编写了函数,但是HTML没有将其拾取,并且该函数返回空值。
如果我在HTML文件中的脚本标记之间布置函数,它将返回正确的时间,但是我需要为赋值样式化它,并且它也必须位于单独的js文件中。
/*here is the js file*/
"use strict";
var $ = function(id) { return document.getElementById(id); };
var displayCurrentTime = function() {
//GET CURRENT DATE-TIME
var currentTime = new Date ();
//GET THE CURRENT TIME
var hours = currentTime.getHours ();
var minutes = currentTime.getMinutes ();
var seconds = currentTime.getSeconds ();
//APPEND A ZERO(0) IF MINUTES OR SECONDS ARE LESS THAN 10
minutes = ( minutes < 10 ? "0" : "" ) + minutes;
seconds = ( seconds < 10 ? "0" : "" ) + seconds;
//CHOOSE AM IF HOUR IS LESS THAN 12 AND PM IF HOUR IS BIGGER THAN 12
var ampm = ( hours < 12 ) ? "AM" : "PM";
//CHANGE TO 12 HOUR FORMAT BY SUBTRACTING 12 IF HOUR IS BIGGER THAN 12.
hours = ( hours > 12 ) ? hours - 12 : hours;
//CHANGE HOUR OF 0 (MIDNIGHT) TO 12.
hours = ( hours == 0 ) ? 12 : hours;
//CREATE STRING OF TIME
var currentTimeString = hours + ":" + minutes + ":" + seconds + " " + ampm;
//DISPLAY TIME IN DIV
document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}
var displayCurrentTime = $("minutes");
console.log(displayCurrentTime);
var padSingleDigit = function(num) {
if (num < 10) { return "0" + num; }
else { return num; }
};
window.onload = function() {
// set initial clock display and then set interval timer to display
// new time every second. Don't store timer object because it
// won't be needed - clock will just run.
displayCurrentTime(setInterval(1000));
};
HTML文件中有4个跨度ID(小时,分钟,秒和安培)需要填写。
这里是index.html文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Clock</title>
<link rel="stylesheet" href="clock.css">
<script src="clock.js"></script>
</head>
<body>
<main>
<h1>Digital clock</h1>
<fieldset>
<legend>Clock</legend>
<span id="hours"> </span>:
<span id="minutes"> </span>:
<span id="seconds"> </span>
<span id="ampm"> </span>
</fieldset>
</main>
</body>
</html>
我发现有一些问题会使您绊倒
1]您将函数定义为displayCurrentTime
(有效),但随后用var displayCurrentTime = $("minutes")
行完全覆盖了它。因此,不用调用函数,而是要检索一个元素-您的console.log()就在后面,所以这就是为什么您看到空值的原因
2)您说“ HTML文件中的4个跨度ID(小时,分钟,秒和安培)需要填写”,但是您的脚本只会返回所有这些字段,并结合在一起-对您没有帮助,但是您确实已经在函数中具有所有正确的值
var displayCurrentTime = function() {
var currentTime = new Date ();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
minutes = ( minutes < 10 ? "0" : "" ) + minutes;
seconds = ( seconds < 10 ? "0" : "" ) + seconds;
var ampm = ( hours < 12 ) ? "AM" : "PM";
hours = ( hours > 12 ) ? hours - 12 : hours;
hours = ( hours == 0 ) ? 12 : hours;
// At this point, all 4 values are ready to drop into your span tags
$('hours').textContent = hours;
$('minutes').textContent = minutes;
$('seconds').textContent = seconds;
$('ampm').textContent = ampm;
}
3)您的setInterval被调用为错误,应该是
window.onload = function() {
setInterval(displayCurrentTime, 1000);
};