close

按此前往javascript完整教學目錄

 

 

DOM2的事件處理模式:

DOM0的事件處理模式有個為人所詬病的不便之處。因為其將事件處理函式當作元件的屬性,所以同樣的事件處裡函式若重複指派,則後指派者會覆蓋掉先指派者,如下例:

<body >

<input type="button"  id="test"  value="按我" />

<input type="text"  id="output"  />

</body>

<script type="text/javascript">

document.getElementById("test").setAttribute("onclick","document.getElementById('output').value+='1';");

document.getElementById("test").setAttribute("onclick","document.getElementById('output').value+='2';");

document.getElementById("test").setAttribute("onclick","document.getElementById('output').value+='3';");

</script>

在執行後、接著按下按鈕之後,文字輸入框中只顯示:3。若設計者希望能夠為一個元件指派多個事件處理函式,則其需用DOM2的事件處理模式。

DOM2的事件處理模式,其用法依瀏覽器及其版本而異。大致上分為兩種:在IE8及其以下版本的瀏覽器為一種,chromefirefoxIE9及其以上版本為另一種。分述如下:

  1. IE8其以下版本中:

語法為:元件.attachEvent("事件處理函式名稱", 無名函式);

其中,無名函式,也有人稱「匿名函式」,即是省略名稱的函式,寫法如:

function (參數一, 參數二…)

{ //函式內容 }

函式內容中,this關鍵字代表觸發該事件之元件本身。

無名函式也可寫為自訂函式的名稱,但其後不得加括號。也就是說,若有個自訂函式為:

function myfunc1()

{ document.write(“hi!”);}

則無名函式可以寫成myfunc1,但若寫成myfunc1()則是錯誤的寫法。或問:若這個自訂函式要輸入參數的話怎麼辦?譬如:

function myfunc2(A,B)

{ document.write(A+B);}

假設要計算A3B4的情況,那只需將無名函式寫成這樣就好了:

function(){myfunc2(3,4);}

範例如:

<body >

<input type="button"  id="test"  value="按我" />

<input type="text"  id="output"  />

</body>

<script type="text/javascript">

document.getElementById("test").attachEvent("onclick",function(){document.getElementById("output").value+='1';});

document.getElementById("test").attachEvent("onclick",function(){document.getElementById("output").value+='2';});

document.getElementById("test").attachEvent("onclick",function(){document.getElementById("output").value+='3';});

</script>

在執行後、接著按下按鈕之後,文字輸入框中會顯示:321

(2) chromefirefoxIE9及其以上版本中:

語法為:元件.addEventListener("事件名稱", 無名函式);

其中,事件名稱並不以on開頭,如clickkeypress…

範例如:

<body >

<input type="button"  id="test"  value="按我" />

<input type="text"  id="output"  />

</body>

<script type="text/javascript">

document.getElementById("test").addEventListener("click",function(){document.getElementById("output").value+='1';});

document.getElementById("test").addEventListener("click",function(){document.getElementById("output").value+='2';});

document.getElementById("test").addEventListener("click",function(){document.getElementById("output").value+='3';});

</script>

在執行後、接著按下按鈕之後,文字輸入框中會顯示:123。注意,其與(1)所說的attachEvent方法相較之下,兩者觸發這三個事件處理函式的順序是相反的。

 

 

上一篇:javascript-事件處理函式

下一篇:javascript cookie 簡介

arrow
arrow

    埃伯 發表在 痞客邦 留言(0) 人氣()