changed 3 years ago
Linked with GitHub

EVENT 事件

tags: Js target

Event 介面表示了一個在 DOM 物件上所發生的事件
可以是由使用者的操作行為所產生(如:點擊滑鼠按鈕或敲打鍵盤)
或是來自 API 因處理非同步任務所產生。

註冊監聽事件 (addEventListener)

<input type="button" class="btn" value="點">
const btn = document.querySelector(".btn"); btn.addEventListener("click", function (e) { console.log('你被點擊了'); })

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

告訴你當下元素資訊 (event 的 e)

當監聽的事件發生時,瀏覽器會去執行我們透過 addEventListener() 註冊的 Event Handler (EventListener) ,也就是我們所指定的 function。

這個時候,EventListener 會去建立一個「事件物件」 (Event Object),裡面包含了所有與這個事件有關的屬性,並且以「參數」的形式傳給我們的 Event Handler:

const btn = document.querySelector(".btn"); btn.addEventListener("click", function (e) { console.log(e); })

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

像是

  • type : 表示事件的名稱
  • target : 表示觸發事件的元素
  • bubbles : 表示這事件是否是在「冒泡」階段觸發 (true / false)
  • pageX / pageY : 表示事件觸發時,滑鼠座標在網頁的相對位置

瞭解目前DOM的HTML位置 (nodeName)

<input type="button" value="+" class="btn">
const btn = document.querySelector(".btn"); console.log(btn.nodeName);

取消默認 (preventDefault)

<a href="https://joe94113.github.io/page/3/">joe</a>
const a = document.querySelector("a"); a.addEventListener("click",function(e){ e.preventDefault(); console.log('123'); })

了解目前所在元素位置 (target)

<input type="button" class="btn" value="點擊">
const a = document.querySelector(".btn"); a.addEventListener("click",function(e){ console.log(e.target); })

e.target 搭配 nodeName 節點,抓到你預期要做的事情

const btn = document.querySelector(".btn"); btn.addEventListener("click",function(e){ console.log(e.target); }) const list = document.querySelector(".list"); list.addEventListener("click",function(e){ console.log(e.target.nodeName); if(e.target.nodeName == "INPUT"){ console.log('你點到按鈕了') }else{ console.log('點哪裡') } })

Select a repo