[JavaScript] Event處理方式的差別 (寫在html內、addEventListener、getElementById)
當使用者對瀏覽器或網頁做出某個動作,就是一個Event
要利用JavaScript來處理Event,有三種方式
1. 寫在HTML內
例: 直接用onclick
2. JavaScript的物件屬性設定
利用javascript的onclick
3. W3C DOM 的addEventListener 利用W3C DOM的addEventListener
這三個方法都會達成一樣的功能,那我們該挑選哪一種實作方式呢?
方法1的優點就是程式很明瞭,而且很簡短。不過最大的缺點就是耦合度會很高
方法2跟方法3在我看來其實差異並不大,不過當你的專案越來越複雜時,就會建議你選擇方法3,因為在方法3中針對同一個物件可以設定 很多個eventListener,而方法2則無法,前面的會被後面的覆蓋過去
要利用JavaScript來處理Event,有三種方式
1. 寫在HTML內
例: 直接用onclick
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<input type="button" onclick"alert('hi!')" value="say hi"> |
2. JavaScript的物件屬性設定
利用javascript的onclick
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
document.getElementById("btn1").onclick=function(){alert("hi")} | |
</script> |
3. W3C DOM 的addEventListener 利用W3C DOM的addEventListener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
document.getElementById("btn1").addEventListener("click", function(){alert("hi")},false); | |
</script> |
方法1的優點就是程式很明瞭,而且很簡短。不過最大的缺點就是耦合度會很高
方法2跟方法3在我看來其實差異並不大,不過當你的專案越來越複雜時,就會建議你選擇方法3,因為在方法3中針對同一個物件可以設定 很多個eventListener,而方法2則無法,前面的會被後面的覆蓋過去
留言
張貼留言