JavaScript target与currentTarget区别
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(如父节点绑定事件,其实子节点触发的事件)
相关推荐
EdwardSiCong 2020-11-23
yungpheng 2020-10-19
jipengx 2020-11-12
橄榄 2020-11-03
lyqdanang 2020-11-02
wservices 2020-10-30
onepiecedn 2020-10-29
数据人 2020-10-26
dfphoto 2020-10-16
hackerlpy 2020-09-07
tianyayi 2020-08-16
Dullonjiang 2020-08-15
fengling 2020-08-15
wordmhg 2020-08-06
guotiaotiao 2020-08-06
zhangsyi 2020-07-28
千锋 2020-07-27
ahnjwj 2020-07-28