removeEventListener
时间: 2023-10-11 11:13:29 浏览: 47
removeEventListener is a method used in JavaScript to remove an event listener that was previously added to an element with the addEventListener method. This is useful when you want to stop listening to a specific event on a specific element.
The syntax for removeEventListener is:
```javascript
element.removeEventListener(event, function, useCapture);
```
- `element`: the element that the event listener was added to.
- `event`: the type of event to remove (e.g. "click", "mouseover", etc.).
- `function`: the function that was used as the event listener.
- `useCapture`: (optional) a boolean value that indicates whether to use event capturing (true) or event bubbling (false) when removing the event listener.
Here's an example:
```javascript
const button = document.querySelector('button');
function handleClick() {
console.log('Button clicked!');
}
button.addEventListener('click', handleClick);
// After some time, we want to remove the event listener
button.removeEventListener('click', handleClick);
```
In this example, we added a click event listener to a button element and assigned a function `handleClick` to it. Later, we removed the event listener using `removeEventListener`. Now, when the button is clicked, the `handleClick` function will no longer be called.