我正在尝试使用JavaScript创建一个工作时钟,但代码将无法运行。我在控制台中收到以下错误:
无法在renderTime
读取null的属性'textContent'
这是HTML:
<html>
<head>
<meta charset="utf-8">
<script src="js/jquery-3.2.1.js" charset="utf-8"></script>
<script src="js/alarm.js" charset="utf-8"></script>
<title>Alarm Clock</title>
</head>
<body>
<div id="clockDisplay" class="clockStyle">3 : 15 : 25 AM</div>
</body>
</html>
这是JavaScript:
function renderTime() {
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
if (h == 0) {
h = 12;
} else if (h < 12) {
h = h - 12;
diem = "PM"
}
if (h < 10) {
h = "0" + h;
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var myClock = document.getElementById('clockDisplay');
myClock.textContent(h + ":" + m + ":" + s + "" + diem);
setTimeout('renderTime()', 1000)
}
renderTime();
答案 0 :(得分:3)
这里的问题是脚本在页面加载之前正在执行。
您只需将js/alarm.js
脚本标记移动到正文标记的末尾,以便在页面完全加载时执行。
textContent
是一个属性,而不是function
,因此您的代码会引发异常,请更改以下行:
myClock.textContent ( h + ":" + m + ":" + s + "" + diem);
要:
myClock.textContent = h + ":" + m + ":" + s + "" + diem;
<强>演示:强>
我重构了您的代码并对其进行了更正,因此需要考虑这些更改,这是一个有效的代码段:
function renderTime(){
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
if (h == 0) {
h = 12;
} else if (h < 12) {
h = h-12;
diem = "PM"
}
if (h < 10) {
h = "0" + h;
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var myClock = document.getElementById('clockDisplay');
myClock.textContent = h + ":" + m + ":" + s + "" + diem;
setTimeout('renderTime()', 1000)
}
renderTime();
<html>
<head>
<meta charset="utf-8">
<script src="js/jquery-3.2.1.js" charset="utf-8"></script>
<title>Alarm Clock</title>
</head>
<body>
<div id="clockDisplay" class="clockStyle">3 : 15 : 25 AM</div>
<script src="js/alarm.js" charset="utf-8"></script>
</body>
</html>
答案 1 :(得分:0)
您收到此错误的原因是当浏览器解析脚本标记时调用该函数。到那时,实际的HTML主体尚未被解析/渲染,并且在dom中确实找不到该元素。
尝试:
<html>
<head>
<meta charset="utf-8">
<script src="js/jquery-3.2.1.js" charset="utf-8"></script>
<script src="js/alarm.js" charset="utf-8"></script>
<title>Alarm Clock</title>
</head>
<body onload="renderTime();">
<div id="clockDisplay" class="clockStyle">3 : 15 : 25 AM</div>
</body>
</html>
然后删除脚本末尾的函数调用。