如何使用 JavaScript HTML DOM 向同一元素添加多个事件处理程序?

front end technologyjavascriptobject oriented programming

在使用 JavaScript 编程时,使用事件非常常见。假设您正在创建一个在单击按钮或使用光标悬停时打开的模式,这里我们在单个元素上使用两个事件,但 JavaScript 没有任何官方方法在单个元素上使用多个事件侦听器。在本文中,我们将学习如何使用 JavaScript HTML DOM 向同一元素添加多个事件处理程序。为了实现这一点,我们提供了以下方法。

  • 使用多个 addEventListener 方法

  • 使用 ES6 方式

使用多个 addEventListener 方法

addEventListener 是一种内置 JavaScript 方法,用于将事件附加到元素。它有三个参数,第一个参数采用字符串格式的事件名称,第二个参数是在触发事件时调用的回调函数,第三个参数是可选的,用于指定是否要捕获事件,它是一个布尔值。您也可以将 addEventListener 与 window 和 document 一起使用。

语法

Event.addEventListener(event, function, useCapture )

参数

  • Event − 它是一个必需参数,以字符串格式指定事件的名称。

  • Function − 它是一个必需参数,在触发事件时调用。

  • 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>

相关文章