Skip to content

Event listener in JavaScript

homepage-banner

Binding Events

The so-called “event listener” refers to adding an event to an element using the addEventListener () method, which we also call “binding events.”

obj.addEventListener(type, fn, false)
  • type: event type
  • fn: anonymous function
  • false: indicates calling during the event bubbling phase
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script>
         window.onload = function () {
             var oBtn = document.getElementById("btn");
             oBtn.addEventListener("click", alertMe, false);
             function alertMe() {
                 alert("this is EventListener click 1");
             };
             oBtn.addEventListener("click", function () {
                 alert("this is EventListener click 2")
             }, false);
         }
    </script>
</head>
<body>
    <input id="btn" type="button" value="按钮"/>
</body>
</html>

Both of the following expressions are acceptable:

obj.addEventListener("click", function () {...}, false);
obj.onclick = function () {...};

Removing Events

obj.removeEventListener(type, fn, false);

Example of using jquery

$(function () {
    $('#clickButton').click(function () {
        fetch("/getReq").then((res)=>{
            return res.json();
        })
            .then((json)=>{
                console.log(json.data)
            })
    })
})
Feedback







Disclaimer
  • Welcome to visit the knowledge base of SRE and DevOps!
  • License under CC BY-NC 4.0
  • Made with Material for MkDocs and improve writing by generative AI tools
  • Copyright issue feedback me#imzye.com, replace # with @