如何在 JavaScript HTML DOM 中向元素添加事件处理程序?

front end technologyjavascriptobject oriented programming

本教程将教您如何在 JavaScript 中向元素添加事件处理程序。有两种方法可以将事件处理程序添加到任何元素,第一种是使用 addEventListener 方法,另一种是使用事件属性。

使用 addEventListener() 方法

addEventListener() 方法用于将事件处理程序附加到任何 DOM 元素。此方法的语法如下。

语法

element.addEventListener( event, function, capture )

参数

  • 事件 − 您想要在元素上应用的事件的名称,例如点击、鼠标悬停、提交等。

  • 函数 - 事件发生后将触发的回调函数。

  • 捕获 - 是否应在捕获阶段执行事件。这将检查并显示布尔值;true 或 false。

返回值:无

示例 1

在此示例中,我们创建一个带有按钮的计数器,每次单击按钮后,我们都会增加计数器值。要监听事件,我们使用 element.addEventListener() 方法。

<html> <head> <title>Example -add an event handler to an element in JavaScript HTML DOM </title> </head> <body> <h2> Adding an event handler to an element in JavaScript HTML DOM using the element.addEventListener method.</h2> <p>Click on the button to increase the counter value by one </p> <button id="btn">Click me</button> <p> <b>Counter: </b> <span id="counter">0</span> </p> </body> <script> // Get the button element let btn = document.getElementById("btn") // Get the counter element let counter = document.getElementById("counter") // Apply the addEventListener method btn.addEventListener("click", () => { // Increase the existing value by 1 // Use the parseInt method to convert the existing // value (which is in string format) into integer counter.innerText = parseInt(counter.innerText) + 1 }) </script> </html>

使用事件侦听器属性添加事件处理程序

浏览器允许我们从 HTML 本身触发事件。HTML 元素具有一些事件属性,例如 onClick、onMouseOver、onSubmit 等。要在触发这些事件后执行任何操作,我们为其分配一些 JavaScript 代码或调用 JavaScript 函数。

示例 2

在此示例中,我们创建一个带有按钮的计数器,每次单击按钮后,我们都会增加计数器值。要侦听事件,我们使用 onclick 属性。

<html> <head> <title>Example program -add an event handler to an element in JavaScript HTML DOM </title> </head> <body> <h2> Adding an event handler to an element in JavaScript HTML DOM using the event attribute.</h2> <p>Click on the button to increase the counter value by one </p> <button id="btn" onclick="increseCounter()">Click me</button> <p> <b>Counter: </b> <span id="counter">0</span> </p> </body> <script> function increseCounter() { // Get the button element let btn = document.getElementById("btn") // Get the counter element let counter = document.getElementById("counter") // Increase the existing value by 1 // Use the parseInt method to convert the existing // value (which is in string format) into integer counter.innerText = parseInt(counter.innerText) + 1 } </script> </html>

在本教程中,我们讨论了两种向 JavaScript HTML DOM 中的元素添加事件处理程序的方法。第一种方法是使用 addEventListener() 方法,第二种方法是使用事件属性。


相关文章