Blogger Information
Blog 3
fans 0
comment 0
visits 2813
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
JavaScript中怎么才能为同一个元素绑定多个不同事件
kongkruye
Original
822 people have browsed it

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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

2.思路来源于:

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

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

4.png

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post