如何解决使用 JS 和 html 显示当前时间时在 printTime 处出现 Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')
2021-10-24
1087
function printTime() {
let clock = document.getElementById("clock"); // use dom to choose a place for the clock
let curr = new Date();
let currtime =
curr.getFullYear() + "/" + (curr.getMonth() + 1) + "/" + curr.getDate();
clock.innerHTML = currtime;
setTimeout("printTime()", 1000);
}
window.onload = function () {
printTime();
};
时间似乎显示正确,但我很好奇 为什么我会收到此错误: lab6.js:6 Uncaught TypeError:无法设置 null 属性(设置“innerHTML”) 在 printTime
当我还在 HTML 代码中添加
<div id="clock"></div>
时?
2个回答
我认为您的代码在这里运行良好
function printTime() {
let clock = document.getElementById("clock"); // use dom to choose a place for the clock
let curr = new Date();
let currtime =
curr.getFullYear() + "/" + (curr.getMonth() + 1) + "/" + curr.getDate();
clock.innerHTML = currtime;
setTimeout("printTime()", 1000);
}
window.onload = function () {
printTime();
};
<div id="clock"></div>
AdityaDees
2021-10-24
我认为您收到错误是因为元素尚未在
window.onload
上呈现。相反,您应该寻找
body.onload
,换句话说,如果您直接在 body 标签中设置对
printTime
的调用,它将正常工作。
<body onload="printTime()">
无论如何,将
printTime()
包装在箭头函数中也可以不出现错误:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<script>
function printTime() {
let clock = document.getElementById("clock"); // use dom to choose a place for the clock
let curr = new Date();
let currtime = curr.getFullYear() + "/" + (curr.getMonth() + 1) + "/" + curr.getDate();
clock.innerHTML = currtime;
setTimeout("printTime()", 1000);
}
window.onload = () => {
printTime();
};
</script>
</head>
<body>
<div id="clock"></div>
</body>
</html>
Telmo Dias
2021-10-24