📅  最后修改于: 2023-12-03 15:29:17.672000             🧑  作者: Mango
In Javascript, addEventListener
is a method that allows you to attach an event handler to an element without overwriting any existing event handlers.
target.addEventListener(type, listener[, options]);
capture
, once
, passive
).const button = document.querySelector('button');
button.addEventListener('click', function() {
console.log('Button clicked!');
});
In this example, we attach a click event listener to a button element using addEventListener
. When the button is clicked, the console.log
statement inside the event listener function will be executed.
One major benefit of using addEventListener
is that multiple event handlers can be attached to the same element. This is useful in cases where you want to perform multiple actions depending on different conditions.
Another benefit is that event listeners added using addEventListener
can be removed using removeEventListener
. This allows you to easily manage your code and prevent potential memory leaks.
Overall, addEventListener
is an essential method in Javascript for attaching event handlers to elements. Its flexibility allows for easy management and customization of code.