如何使用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>
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP