<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代码javascript
<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>