javascript - How to solve the error Cannot set property 'value' of null when executing a js function?
phpcn_u1582
phpcn_u1582 2017-06-12 09:25:38
0
1
1430
<!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?

phpcn_u1582
phpcn_u1582

reply all(1)
代言

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!