javascript - js执行函数报错Cannot set property 'value' of null怎么解决?
本文介绍了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);
也是可以运行的,这是为什么呢?
解决方案
dom还没有完全加载完成原因,所以js建议放在body下面执行,或者用window.onload就能放在head头部执行。
这篇关于javascript - js执行函数报错Cannot set property 'value' of null怎么解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文