1、DOM事件绑定到父元素
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>target 与 currentTarget</title>
</head>
<body>
<ul id="ul">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script type="text/javascript">
var ul = document.getElementById('ul');
ul.onclick = function(e) {
console.log(this); //ul DOM节点
console.log(this === e.target); // click 事件真正的目标 false
console.log(this === e.currentTarget); //在事件处理程序内部,对象 this 始终等于 currentTarget 的值 返回ture
}
</script>
</body>
</html>
2、DOM事件绑定到本身DOM上
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>target 与 currentTarget</title>
</head>
<body>
<ul id="ul">
<li id="li">1</li>
<li>2</li>
<li>3</li>
</ul>
<script type="text/javascript">
var li = document.getElementById('li');
li.onclick = function(e) {
console.log(this); //li DOM节点
console.log(this === e.target); // click 事件真正的目标 true
console.log(this === e.currentTarget); //在事件处理程序内部,对象 this 始终等于 currentTarget 的值 返回ture
}
</script>
</body>
</html>
总结:
(1)事件内部的this就是绑定事件的那个DOM
(2)事件处理程序内部,对象 this 始终等于 currentTarget 的值。
(3)事件处理程序内部,target 的值是实际触发事件的真正DOM(如父节点绑定事件,其实子节点触发的事件)
更新2019.1.3
上面说的真晦涩!
示例代码:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>target 和 currentTarget 区别</title>
</head>
<body>
<div id="app1">
<div id="app2">
<div id="app3">
test
</div>
</div>
</div>
<script type="text/javascript">
let app1 = document.getElementById('app1'),
app2 = document.getElementById('app2'),
app3 = document.getElementById('app3');
app1.addEventListener('click', e => {
console.log(e.target, 'e.target')
console.log(e.currentTarget, 'e.currentTarget')
})
</script>
</body>
</html>
效果:
看明白了没?
这个的使用场景是:事件代理。
真正触发事件的dom是target
可以将事件代理到currentTarget上。