[英]How to solve Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') at printTime when trying to show current time with JS and html
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();
};
It seems like the time displays correctly but I am curious why am I getting this error: lab6.js:6 Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') at printTime似乎时间显示正确,但我很好奇为什么会出现此错误:lab6.js:6 Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') at printTime
when I also added <div id="clock"></div>
in the HTML code?当我还在 HTML 代码中添加
<div id="clock"></div>
时?
I think your code is working fine here我认为你的代码在这里工作正常
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>
In my opinion you get the error because the element is not yet rendered on the window.onload
.在我看来,您收到错误是因为该元素尚未在
window.onload
上呈现。 Instead you should be looking for body.onload
, or in other words, if you would set the call to printTime
directly in the body tag, it would work fine.相反,您应该寻找
body.onload
,或者换句话说,如果您直接在 body 标签中设置对printTime
的调用,它会正常工作。
<body onload="printTime()">
In any case, wrapping the printTime()
inside an arrow function also works without the error :在任何情况下,将
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.