JavaScript--addEventListener() method

For the addEventListener() method, it is used to add an event listener to the specified element, and execute the corresponding function or code when the specified event is triggered on the element. This method has the following syntax:

element.addEventListener(event, listener[, options]);
  1. element: The element object to add the event listener to.
  2. event: The event type to listen to, such as "click", "mousemove", etc.
  3. listener: The function or callback function to be executed when the event is triggered.
  4. options: is an optional parameter used to configure some options of the event, such as whether to use the capture (capture) phase.

Here is an example showing how to add a click event listener to a button using the addEventListener() method:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <button id="myButton">点击我</button>

<script>
    var button = document.getElementById("myButton");

    button.addEventListener("click", function(){
        console.log("按钮被点击了!");
    });
</script>
</body>
</html>

In the above example, we get the button element whose id is "myButton" through the getElementById() method, and then use the addEventListener() method to add a click event listener to the button. When the button is clicked, the anonymous function will execute and output the message "Button was clicked!" to the console.

Guess you like

Origin blog.csdn.net/m0_74293254/article/details/131718081