JavaScript如何为同一个元素绑定多个不同事件,指向同一个事件处理函数

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44253336/article/details/98759854

1.源码:

<body>
<input type="button" value="点击" id="btn">


<script>
    //为同一个元素绑定多个不同的事件,指向相同的事件处理函数
    document.getElementById("btn").onclick = f1;
    document.getElementById("btn").onmouseover = f1;
    document.getElementById("btn").onmouseout = f1;

    function f1(e) {
        switch (e.type) {
            case "click":
                alert("hehe");
                break;
            case "mouseover":
                this.style.backgroundColor = "red";
                break;
            case "mouseout":
                this.style.backgroundColor = "yellow";
                break;
        }
    }
</script>
</body>

2.思路来源于:

  document.getElementById("btn").onclick = function (e) {
                console.log(e);
        };
        // type: "click"

在事件参数对象中,里面有很多属性,当我们把它输出后可以看到有一个属性为type: “click”。不同事件里面的type类型值都是不一样的。用switch语句我们就可以根据type值自动选择不同的事件进行处理。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44253336/article/details/98759854