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