直接上程式碼。
Firefox 版本
<HTML>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<HEAD>
<TITLE></TITLE>
<script>
document.onclick = function (e) {
var evt = e || window.event;
var tar = evt.target || evt.srcElement;
if ((tar.tagName.toLowerCase() == "input" && tar.type == "button") ||
tar.tagName.toLowerCase() == "button") {
alert("你點擊的是一個按鈕");
}
};
</script>
</HEAD>
<BODY>
<input id="button1" type="button" value="1111"/>
<input id="button2" type="button" value="2222"/>
<input id="button3" type="button" value="3333"/>
<input id="button4" type="button" value="4444"/>
</BODY>
</HTML>
Chrome 版本
<HTML>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<HEAD>
<TITLE></TITLE>
<script>
document.onclick = function () {
var obj = event.srcElement;
if (obj.type == "button") {
alert(obj.id);
}
};
</script>
</HEAD>
<BODY>
<input id="button1" type="button" value="1111"/>
<input id="button2" type="button" value="2222"/>
<input id="button3" type="button" value="3333"/>
<input id="button4" type="button" value="4444"/>
</BODY>
</HTML>
兩個版本的差異其實只在事件物件的取得方式:標準瀏覽器透過參數 e 傳入,並用 e.target 取得實際觸發的元素;舊 IE 則要從 window.event 與 srcElement 拿。實務上把兩者寫成 e = e || window.event、tar = evt.target || evt.srcElement,就能同時相容兩邊,不必維護兩份程式碼。