如何在 JavaScript HTML DOM 中向元素添加事件处理程序?
front end technologyjavascriptobject oriented programming更新于 2024/5/19 17:05:00
本教程将教您如何在 JavaScript 中向元素添加事件处理程序。有两种方法可以将事件处理程序添加到任何元素,第一种是使用 addEventListener 方法,另一种是使用事件属性。
使用 addEventListener() 方法
addEventListener() 方法用于将事件处理程序附加到任何 DOM 元素。此方法的语法如下。
语法
element.addEventListener( event, function, capture )
参数
事件 − 您想要在元素上应用的事件的名称,例如点击、鼠标悬停、提交等。
函数 - 事件发生后将触发的回调函数。
捕获 - 是否应在捕获阶段执行事件。这将检查并显示布尔值;true 或 false。
返回值:无
示例 1
在此示例中,我们创建一个带有按钮的计数器,每次单击按钮后,我们都会增加计数器值。要监听事件,我们使用 element.addEventListener() 方法。
Adding an event handler to an element in JavaScript HTML DOM using the element.addEventListener method.
Click on the button to increase the counter value by one
Counter:
0
// 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
})
使用事件侦听器属性添加事件处理程序
浏览器允许我们从 HTML 本身触发事件。HTML 元素具有一些事件属性,例如 onClick、onMouseOver、onSubmit 等。要在触发这些事件后执行任何操作,我们为其分配一些 JavaScript 代码或调用 JavaScript 函数。
示例 2
在此示例中,我们创建一个带有按钮的计数器,每次单击按钮后,我们都会增加计数器值。要侦听事件,我们使用 onclick 属性。
Adding an event handler to an element in JavaScript HTML DOM using the event attribute.
Click on the button to increase the counter value by one
Counter:
0
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
}
在本教程中,我们讨论了两种向 JavaScript HTML DOM 中的元素添加事件处理程序的方法。第一种方法是使用 addEventListener() 方法,第二种方法是使用事件属性。
相关文章
JavaScript 中的常规函数与箭头函数?
如何使用 JavaScript 对象自己的原型来访问它?
JavaScript 的布尔函数?
JavaScript 中的 Object.assign()?
JavaScript 数组中的第一个元素和最后一个元素?
JavaScript 是传递引用还是传递值的语言?
如何在 JavaScript 中深度复制对象?
在 JavaScript 中使用"weakMap.has()"方法?
在 Javascript 中向函数传递未知数量的参数
JavaScript 中用户位置的经纬度?
打印
下一节 ❯❮ 上一节