如何使用 JavaScript HTML DOM 向同一個元素新增多個事件處理程式?


在 JavaScript 程式設計中使用事件非常常見。假設您正在建立一個模態框,它在單擊按鈕或滑鼠懸停時開啟,這裡我們在單個元素上使用了兩個事件,但 JavaScript 沒有官方方法在一個元素上使用多個事件監聽器。在本文中,我們將學習如何使用 JavaScript HTML DOM 向同一個元素新增多個事件處理程式。為了實現這一點,我們有以下幾種方法。

  • 使用多個 addEventListener 方法

  • 使用 ES6 方法

使用多個 addEventListener 方法

addEventListener 是一個內建的 JavaScript 方法,用於將事件附加到元素。它有三個引數:第一個引數以字串格式接收事件名稱;第二個引數是當事件觸發時呼叫的回撥函式;第三個引數是可選的,用於指定是否要捕獲事件,它是一個布林值。您也可以將 addEventListener 與 window 和 document 一起使用。

語法

Event.addEventListener(event, function, useCapture )

引數

  • 事件 − 這是必需的引數,以字串格式指定事件的名稱。

  • 函式 − 這是必需的引數,當事件觸發時會被呼叫。

  • useCapture − 這是一個可選引數,指定事件處於冒泡階段還是捕獲階段。其型別為布林值。

注意 − 事件名前不要使用“on”。例如:寫“click”而不是“onclick”。

方法

為了在一個元素上新增多個事件監聽器,我們多次呼叫 addEventListener 方法,並傳入多個事件,但是每次傳入的函式都應該相同。

示例

在這個例子中,我們有一個按鈕,我們在點選按鈕或滑鼠懸停在按鈕上時增加計數器。

<html> <head> <title> Example -add many Event Handlers to the same element with JavaScript HTML DOM </title> </head> <body> <h2> Adding many Event Handlers to the same element with JavaScript HTML DOM ? </h2> <p> Click or mouse over the button to increase the counter </p> <h1>Counter: <span id="counter"> 0 </span> </h1> <button id="btn" >Increse ++</button> </body> <script> // Get the button and counter let btn = document.getElementById("btn") let counter = document.getElementById("counter"); // Call the addEventListener method btn.addEventListener("mousemove", increase) btn.addEventListener("click", increase) // Define the increase function function increase(){ counter.innerText = parseInt(counter.innerText) + 1 } </script> </html>

使用 ES6 方法

在這種方法中,我們也使用 addEventListener,但是我們只調用一次,而不是多次呼叫。在這種方法中,我們使用以下步驟。

  • 將所有事件新增到陣列中。

  • 將 forEach 方法應用於陣列,然後在每次迭代中使用該元素(即事件名稱)呼叫 addEventListener。

示例

在這個例子中,我們有一個按鈕,我們在點選按鈕或滑鼠懸停在按鈕上時增加計數器。

<html> <head> <title>Example- add many Event Handlers to the same element with JavaScript HTML DOM </title> </head> <body> <h2> Adding many Event Handlers to the same element with JavaScript HTML DOM? </h2> <p> Click or mouse over the button to increase the counter </p> <h1>Counter: <span id="counter"> 0 </span> </h1> <button id="btn">Increse ++</button> </body> <script> // Get the button and counter let btn = document.getElementById("btn") let counter = document.getElementById("counter"); // Call the addEventListener method ["click", "mousemove"].forEach((event) => { btn.addEventListener(event, increase) }) // Define the increase function function increase() { counter.innerText = parseInt(counter.innerText) + 1 } </script> </html>

更新於:2022年8月22日

11K+ 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告