临风流烟
2016-11-02 00:40
<!DOCTYPE HTML> <html> <head> <script type="text/javascript"> var num=0; // numCount(); function numCount(){ document.getElementById('txt').value=num; num=num+1; setTimeout("numCount()",1000); } </script> </head> <body> <form> <input type="text" id="txt" /> <input type="button" value="Start" onclick="numCount()" /> </form> </body> </html>
为什么我把onclick="numCount()"删除,然后在script标签中加上numCount()就报错,
提示cannot set property 'value' of null
因为页面加载顺序从上到下,当执行numCount函数,加载到document.getElementById('txt').value=num这一句时,body里面的代码还未获取,因此会报错,只要将整个<script>标签放到</body>上方即可,
<!DOCTYPE HTML> <html> <head> </head> <body> <form> <input type="text" id="txt" /> <input type="button" value="Start" /> <!--删除了onclick="numCount()"--> </form> <script type="text/javascript"> var num=0; numCount(); //页面加载时立刻执行numCount() function numCount(){ document.getElementById('txt').value=num; num=num+1; setTimeout("numCount()",1000); } </script> </body> </html>
JavaScript进阶篇
468194 学习 · 21891 问题
相似问题
回答 1
回答 3
回答 1
回答 1
回答 1