dispatchEvent
时间: 2024-05-07 17:15:28 浏览: 38
DispatchEvent
The `dispatchEvent()` method is a built-in method in JavaScript that allows you to trigger a specific event on a DOM element. This method is used to simulate user actions, such as clicks, mouseovers, and key presses.
The `dispatchEvent()` method takes an Event object as an argument, which can be created using the `Event()` constructor. The `Event()` constructor takes two parameters: the first is the type of event you want to create (e.g., "click", "mousemove", "keydown"), and the second is an object that contains any event-specific options (e.g., the key code for a keydown event).
Here's an example of how to use the `dispatchEvent()` method to trigger a click event on a button:
```javascript
const button = document.querySelector('button');
const clickEvent = new Event('click');
button.dispatchEvent(clickEvent);
```
This code selects a button element on the page, creates a new click event using the `Event()` constructor, and dispatches the event on the button using the `dispatchEvent()` method. This will simulate a user clicking on the button.
阅读全文