通常的網(wǎng)頁編程原則是把形式,內(nèi)容和表現(xiàn)分開,這樣頁面組件的事件處理就轉(zhuǎn)移到了
window.onload或是Dom.onready中,寫在一起。
有時(shí),如果對頁面組建進(jìn)行刪除或是更改id,會(huì)導(dǎo)致js出現(xiàn)錯(cuò)誤,找不到組件,結(jié)果下面的正確js也無法執(zhí)行了。
在進(jìn)行頁面調(diào)整階段這個(gè)問題很常見。
當(dāng)然,修改過來是正確的做法,另外我們還可以通過組件檢測來做,這樣的好處是頁面調(diào)整后,js無需改變。
以下代碼供參考:
window.onload或是Dom.onready中,寫在一起。
有時(shí),如果對頁面組建進(jìn)行刪除或是更改id,會(huì)導(dǎo)致js出現(xiàn)錯(cuò)誤,找不到組件,結(jié)果下面的正確js也無法執(zhí)行了。
在進(jìn)行頁面調(diào)整階段這個(gè)問題很常見。
當(dāng)然,修改過來是正確的做法,另外我們還可以通過組件檢測來做,這樣的好處是頁面調(diào)整后,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>
<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>