为同一个元素,添加相同名字的处理函数的不同绑定事件—通过switch语法

要点:

1.switch语法跟break语法结合使用,才能达到效果,满足条件后,执行出路函数,然后跳出循环。

2.这里的.type是返回的是事件的绑定类型,如click。区别与typeof 判断的是值的类型,如 "undefined"。

代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<input type="button" value="点我不花一分钱" id="btn">

	<script type="text/javascript">
		function myGet(id){
			return document.getElementById(id);
		}
        
        myGet("btn").onclick = f1;
        myGet("btn").onmouseover = f1;
        myGet("btn").onmouseout = f1;

        function f1(e){
        	switch (e.type){
        	   //通过.type判断事件的类型,而做出相应的switch和case对应的操作
               case "click": alert("装备不花一分钱");
               break;
               case "mouseover": this.style.backgroundColor = "blue";
               break;
               case "mouseout": this.style.backgroundColor = "yellow";
        	}
        	// 这里一定要注意,绑定事件类型的名字本来前面就不带on,这是微软的特例,其他浏览器是为了兼容
        }
	</script>
</body>
</html>

效果:

猜你喜欢

转载自blog.csdn.net/qq_42036616/article/details/83780852