Eclpise下配置MyEclipse的Tomcat (圖解)

<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>

IE實現的DOM事件流

今天突然看到了IE中的event,於是想起來了DOM中的事件流。原來大概知道IE實現了冒泡的事件流模型。但是具體怎麼樣卻忘記了。“好奇害死貓”啊——爲了這個臨時的問題花了一個多小時啊。下面先介紹IE5.5以上實現的事件流模型。

冒泡模型:DOM模型是一個樹狀模型,舉例來說,如下面的代碼

 

<div onclick="alert('div1')">
       
<onclick="alert('a1'); ">aaa</a>
</div>

 

div裏面嵌套了一個a標籤。冒泡模型指的就是事件會從內部的對象逐漸向外部傳遞。對於上面的代碼,點擊鏈接aaa,那麼首先會執行<a>onclick事件彈出“a1”,然後是<div>onclick事件彈出”div1”IE提供了取消事件“冒泡”的機制,即設置event.cancelBubble=true,默認這個值爲false,即事件冒泡傳遞。下面的代碼將只會執行<a>onclick事件。
<div onclick="alert('div1')">
  
<onclick="alert('a1'); event.cancelBubble=true;">aaa</a>
</div>

 

 

注意這裏設置的取消事件冒泡傳遞只是針對於當前的事件。具體說來如下面的代碼:

 

<script>var g = 0;</script>       
<div onclick="alert('div1')">
<onclick="alert('a1'); if(g++ == 0)event.cancelBubble=true;">aaa</a>
</div>

 

 

第一次點擊鏈接的時候,全局變量g==0,所以會取消事件向外傳遞,也就是divonclick事件不會執行,此時g=1。第二次點擊鏈接的時候,不會再設置event.cancelBubble=true,所以事件仍然向外傳遞,即divonclick事件會執行。

 

       捕獲模型:如果要動態添加或刪除DOM元素的事件處理函數的話,用上面的方法肯定是不方便的。因此每個對象都有attachEventdetachEvent兩個方法用於增加和移除事件綁定。微軟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)之後響應,如果捕獲事件綁定多個函數的話,不能保證這些函數的執行順序。

對於下面的代碼:

<script>var g = 0;</script>  
<div onclick="alert('div1')">
<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自家的不一致,以後再介紹。

 
發佈了58 篇原創文章 · 獲贊 0 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章