一、DOM事件綁定到父元素javascript
<!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>
二、DOM事件綁定到自己DOM上html
<!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>
總結:java
(1)事件內部的this就是綁定事件的那個DOMapp
(2)事件處理程序內部,對象 this 始終等於 currentTarget 的值。dom
(3)事件處理程序內部,target 的值是實際觸發事件的真正DOM(如父節點綁定事件,其實子節點觸發的事件)ui
更新2019.1.3 this
上面說的真晦澀!spa
示例代碼:3d
<!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上。