通常的網頁編程原則是把形式,內容和表現分開,這樣頁面組件的事件處理就轉移到了
window.onload或是Dom.onready中,寫在一起。
有時,如果對頁面組建進行刪除或是更改id,會導致js出現錯誤,找不到組件,結果下面的正確js也無法執行了。
在進行頁面調整階段這個問題很常見。
當然,修改過來是正確的做法,另外我們還可以通過組件檢測來做,這樣的好處是頁面調整后,js無需改變。
以下代碼供參考:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
</head>
<body>
<button id="btn1">BTN1</button>
<br/>
<button id="btn2">BTN2</button>
</body>
</html>
<script type="text/javascript">
<!--
if(document.getElementById("btn1")){
document.getElementById("btn1").onclick=function(){
alert(1);
};
}
if(document.getElementById("btn2")){
document.getElementById("btn2").onclick=function(){
alert(2);
};
}
//-->
</script>