Home  >  Q&A  >  body text

javascript - How to solve the error Cannot set property 'value' of null when executing a js function?

<!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_u1582phpcn_u15822687 days ago1425

reply all(1)I'll reply

  • 代言

    代言2017-06-12 09:27:38

    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.

    reply
    0
  • Cancelreply