Skip to content

Event listener in JavaScript

绑定事件

所谓的“事件监听器”,指的是使用addEventListener()方法为一个元素添加事件,我们又称之为“绑定事件”。

obj.addEventListener(type, fn, false)
  • type: 事件类型
  • fn: 匿名函数
  • false: 表示事件冒泡阶段调用
<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>

以下两种表示均可

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

解绑事件

obj.removeEventListener(type, fn, false);

jquery 用法举例

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

Disclaimer
  1. License under CC BY-NC 4.0
  2. Copyright issue feedback: dig +short txt issue.imzye.com
  3. Not all the commands and scripts are tested in production environment, use at your own risk
  4. No privacy information is collected here
Buy Me a Coffee