<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>计时器</title>
<script type="text/javascript">
var num=0;
function startCount() {
document.getElementById('count').value=num;
num=num+1;
setTimeout(startCount(),1000);
}
startCount();
</script>
</head>
<body>
<form>
<input type="text" id="count" />
</form>
</body>
</html>
Why can’t I write startCount() directly on line 13? Prompt error Uncaught TypeError: Cannot set property 'value' of null
. If I write a script tag below the html tag and write startCount()
in it, it will work again, or if I write setTimeout(startCount(),1000);
on line 13, it will also work. Why?
The reason is that the dom has not been completely loaded, so it is recommended to execute js under the body, or use window.onload to execute it in the head.