Javascript中事件對(duì)象的target和this的區(qū)別
1、當(dāng)觸發(fā)對(duì)象與綁定對(duì)象一致時(shí)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <ul> <li>item1</li> <li>item2</li> <li>item3</li> <li>item4</li> <li>item5</li> </ul> <script> const li=document.querySelector("ul li:nth-of-type(4)"); console.log(li); li.addEventListener("click",function(e){ console.log(e.target); console.log(this); }); </script> </body> </html>
點(diǎn)擊item4這個(gè)li后,兩者返回如下:
2、當(dāng)觸發(fā)對(duì)象與綁定對(duì)象不一致時(shí)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <ul> <li>item1</li> <li>item2</li> <li>item3</li> <li>item4</li> <li>item5</li> </ul> <script> const ul=document.querySelector("ul"); console.log(ul); ul.addEventListener("click",function(e){ console.log(e.target); console.log(this); }); </script> </body> </html>
點(diǎn)擊item4這個(gè)li后,輸出如下:
3、總結(jié):
target返回的是事件觸發(fā)對(duì)象
this 返回的是事件綁定對(duì)象