IE實現的DOM事件流
今天突然看到了IE中的event,於是想起來了DOM中的事件流。原來大概知道IE實現了冒泡的事件流模型。但是具體怎麼樣卻忘記了。“好奇害死貓”啊——爲了這個臨時的問題花了一個多小時啊。下面先介紹IE5.5以上實現的事件流模型。
冒泡模型:DOM模型是一個樹狀模型,舉例來說,如下面的代碼
<a onclick="alert('a1'); ">aaa</a>
</div>
div裏面嵌套了一個a標籤。冒泡模型指的就是事件會從內部的對象逐漸向外部傳遞。對於上面的代碼,點擊鏈接aaa,那麼首先會執行<a>的onclick事件彈出“a1”,然後是<div>的onclick事件彈出”div1”。IE提供了取消事件“冒泡”的機制,即設置event.cancelBubble=true,默認這個值爲false,即事件冒泡傳遞。下面的代碼將只會執行<a>的onclick事件。
<a onclick="alert('a1'); event.cancelBubble=true;">aaa</a>
</div>
注意這裏設置的取消事件冒泡傳遞只是針對於當前的事件。具體說來如下面的代碼:
<div onclick="alert('div1')">
<a onclick="alert('a1'); if(g++ == 0)event.cancelBubble=true;">aaa</a>
</div>
第一次點擊鏈接的時候,全局變量g==0,所以會取消事件向外傳遞,也就是div的onclick事件不會執行,此時g=1。第二次點擊鏈接的時候,不會再設置event.cancelBubble=true,所以事件仍然向外傳遞,即div的onclick事件會執行。
捕獲模型:如果要動態添加或刪除DOM元素的事件處理函數的話,用上面的方法肯定是不方便的。因此每個對象都有attachEvent和detachEvent兩個方法用於增加和移除事件綁定。微軟DHTML幫助文檔對attachEvent方法的描述如下:
bSuccess = object.attachEvent(sEvent, fpNotify)
Syntax
bSuccess = object.attachEvent(sEvent, fpNotify)
Parameters
sEvent |
Required. String that specifies any of the standard DHTML Events. |
fpNotify |
Required. Pointer that specifies the function to call when sEvent fires. |
Return Value
Boolean. Returns one of the following possible values:
true |
The function was bound successfully to the event. |
false |
The function was not bound to the event. |
Remarks
When sEvent fires on the object, the object's sEvent handler is called before fpNotify , the specified function. If you attach multiple functions to the same event on the same object, the functions are called in random order, immediately after the object's event handler is called.
上面說的關鍵點是捕獲事件(fpNotify)在原始事件(sEvent)之後響應,如果捕獲事件綁定多個函數的話,不能保證這些函數的執行順序。
對於下面的代碼:
<div onclick="alert('div1')">
<a onclick="alert('a1'); if(g++ == 0)event.cancelBubble=true;">aaa</a>
</div>
<script>
document.all.tags("a")[0].attachEvent("onclick", function (){alert("a2");});
document.all.tags("a")[0].attachEvent("onclick", function (){alert("a3");});
document.all.tags("a")[0].attachEvent("onclick", function (){alert("a4");});
</script>
在我的瀏覽器IE6中,點擊鏈接首先會彈出”a1”,然後分別彈出”a3”,”a4”,”a2”。
FireFox等其他瀏覽器多半實現的是DOM2的標準事件流,與IE自家的不一致,以後再介紹。