firefox中addEventListener()方法和ie中attachEvent()方法都是為HTML元素添加一個事件監聽
為什麼要採用事件監聽而不是直接對元素的事件屬性(如:onclick、onmouseover)賦值?
這兩種方法處理事件還是有很大區別的!事件屬性只能賦值一種方法,即:
button1.onclick = function() { alert(1); };
button1.onclick = function() { alert(2); };
這樣後面的指派陳述式就將前面的onclick屬性覆蓋了。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Coda Bubble Example</title>
</head>
<body>
<button id="Button1">測試</button>
<script type="text/javascript">
/// <summary>
/// 添加事件監聽
/// </summary>
/// <param name="target">載體</param>
/// <param name="type">事件類型</param>
/// <param name="func">事件函數</param>
function addEventHandler(target, type, func) {
if (target.addEventListener)
target.addEventListener(type, func, false);
else if (target.attachEvent)
target.attachEvent("on" + type, func);
else target["on" + type] = func;
}
/// <summary>
/// 移除事件監聽
/// </summary>
/// <param name="target">載體</param>
/// <param name="type">事件類型</param>
/// <param name="func">事件函數</param>
function removeEventHandler(target, type, func) {
if (target.removeEventListener)
target.removeEventListener(type, func, false);
else if (target.detachEvent)
target.detachEvent("on" + type, func);
else delete target["on" + type];
}
var Button1 = document.getElementById("Button1");
var Button1Click = function() { alert(1); };
addEventHandler(Button1, "click", Button1Click);
addEventHandler(Button1, "click", function() { alert(2); } );
addEventHandler(Button1, "click", function() { alert(3); } );
removeEventHandler(Button1, "click", function() { alert(2); } ); // 移不出
removeEventHandler(Button1, "click", Button1Click); // 可以移除
</script>
</body>
</html>
而添加事件監聽就可以並行。
特別是當團隊合作時,事件並行的需求增多,比如:監聽document對象的滑鼠事件或者window對象的載入事件等。
使用事件屬性則很容易造成事件覆蓋掉。
經過測試IE(8)中先顯示3再顯示2,而firefox(3)中則先顯示2再顯示3
這個是為什麼呢?測試的結果即真理,沒啥好想的。囧