document.getElementById(...) is null
<html>
<head>
<script type="text/javascript">
document.getElementById('btn1').onclick=function(){
alert('helleo');
};
</script>
</head>
<body>
<input type="button" name="name" value="button" id="btn1"/>
</body>
</html>
如果js代码像上面这样写就会报错:document.getElementById(...) is null,原因是按从上到下得执行顺序,执行js代码得时候还没有注册id为btn1得button,所以根据id获得得对象就为空,所以得将上面得js代码写到一个window.onload方法里面,意思是页面加载完毕以后再执行内部得js代码
<html>
<head>
<script type="text/javascript">
window.onload=function(){
document.getElementById('btn1').onclick=function(){
alert('helleo');
};
};
</script>
</head>
<body>
<input type="button" name="name" value="button" id="btn1"/>
</body>
</html>

浙公网安备 33010602011771号