登录

javascript - js执行函数报错Cannot set property 'value' of null怎么解决?

<!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>

为什么13行直接写startCount()不行呢?提示报错Uncaught TypeError: Cannot set property 'value' of null。我在html标签下方写一个script标签,里面写startCount()又可以了,或者13行写成setTimeout(startCount(),1000);也是可以运行的,这是为什么呢?

# JavaScript
phpcn_u1582phpcn_u15822122 天前1003 次浏览

全部回复(1) 我要回复

  • 代言

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

    dom还没有完全加载完成原因,所以js建议放在body下面执行,或者用window.onload就能放在head头部执行。

    回复
    0
  • 取消回复发送