event.target和this的区别

16 篇文章 0 订阅
8 篇文章 0 订阅
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			
			.box1{
				width: 200px;
				height: 200px;
				background-color: black;
			}
			.box2{
				width: 100px;
				height: 100px;
				background-color: red;
			}
			.box3{
				width: 50px;
				height: 50px;
				background-color: blue;
			}
		</style>
		<script type="text/javascript">
			window.onload=function(){
				var box1=document.getElementsByClassName("box1")[0];
				var box2=document.getElementsByClassName("box2")[0];
				var box3=document.getElementsByClassName("box3")[0];
				box1.onclick=function(event){
					event=event||window.event;
					alert(event.target.className);
//					alert(this.className);
				}
				box2.onclick=function(event){
					event=event||window.event;
					alert(event.target.className);
//					alert(this.className);
				}
				box3.onclick=function(event){
					event=event||window.event;
					alert(event.target.className);
//					alert(this.className);
				}
			}
		</script>
	</head>
	<body>
		<div class="box1">
			<div class="box2">
				<div class="box3">
					
				</div>
			</div>
		</div>
	</body>
</html>

运行这个DEMO,在事件冒泡的背景下,点击box3,event.target.className为box3,之后冒泡的事件弹出的信息也为box3;这是因为event.target指向的是被触发事件(被点击)的对象(box3),仅通过box3触发了一次事件(点击),所以只弹出一次box3;而this.name则依次弹出的为box3,box3,box1,这是因为this指向的是事件绑定的对象,事件冒泡中连续触发了三次事件,这三次事件绑定的对象都不同。

(可能说的有点复杂………)

简单的说就是,你点击了box3,那么e.target就是box3;并且由于你点击了box3,通过点击box3冒泡触发了box1,box2,

在box1和box2的事件中,e.target也是box3。但是this是谁,就和由谁触发了事件无关了。比如,无论是box2,还是box3触发了box1的事件,还是box1的事件根本没有被触发,box1的事件的this永远都是box1,忠心耿耿;

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值