站长图库向大家介绍了Javascript,事件对象,target和this的区别等相关知识,希望对您有所帮助
Javascript中事件对象的target和this的区别
1、当触发对象与绑定对象一致时
<!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>
点击item4这个li后,两者返回如下:
2、当触发对象与绑定对象不一致时
<!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>
点击item4这个li后,输出如下:
3、总结:
target返回的是事件触发对象
this 返回的是事件绑定对象