区别
Use event.currentTarget instead of event.target because of event bubbling/capturing:
- event.currentTarget- is the element that has the event listener attached to.
- event.target- is the element that triggered the event.
尽可能使用event.currentTarget获取事件点击元素,而不是event.target
- event.currentTarget- 监听事件绑定的元素
- event.target- 触发事件的元素。事件可能冒泡到父元素,随意触发事件的可能是父元素。
测试代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<style>
#parent {
background-color: red;
width: 250px;
height: 220px;
}
#child {
background-color: yellow;
height: 120px;
width: 120px;
margin: 0 auto;
}
#grand-child {
background-color: blue;
height: 50px;
width: 50px;
margin: 0 auto;
}
#msg,
#jQmsg,
#arrmsg {
font-size: 16px;
font-weight: 600;
background-color: #eee;
font-family: sans-serif;
color: navy;
}
</style>
</head>
<body>
<div id="parent">Parent-(attached event handler)<br><br>
<div id="child"> Child<br><br>
<p id="grand-child">Grand Child</p>
</div>
</div>
<div id="msg"></div><br>
<div id="jQmsg"></div><br>
<div id="arrmsg"></div>
</body>
<script type="text/javascript">
(function() {
var parent = document.getElementById('parent');
parent.addEventListener('click', function(e) {
document.getElementById('msg').innerHTML = "this: " + this.id +
"<br> currentTarget: " + e.currentTarget.id +
"<br>target: " + e.target.id;
});
$('#parent').on('click', function(e) {
$('#jQmsg').html("*jQuery<br>this: " + $(this).prop('id')
+ "<br>currenTarget: " + $(e.currentTarget).prop('id')
+ "<br>target: " + $(e.target).prop('id'));
});
$('#parent').on('click', e => $('#arrmsg').html('*Arrow function <br> currentTarget: ' + e.currentTarget.id));
})();
</script>
</html>
测试结果
case1:点击grand child
target: 触发事件的是parent.
currentTarget:绑定
case2
点击黄色child。
1 target 触发元素chilid
2 currenttarget 是parent