如何使用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