When learning event objects, I always think that target
and this
are the same. It was not until later that I discovered that the difference between the two is quite big. Today I will take you through Get up and take a look.
1. When the trigger object is consistent with the binding object
<!DOCTYPE html> <html lang="en"> <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 class="list"> <li class="itm">item1</li> <li class="itm">item2</li> <li class="itm">item3</li> <li class="itm">item4</li> <li class="itm">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>
Click on item4
this## After #li, both return as follows:
2. When the trigger object is inconsistent with the binding object
<!DOCTYPE html> <html lang="en"> <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 class="list"> <li class="itm">item1</li> <li class="itm">item2</li> <li class="itm">item3</li> <li class="itm">item4</li> <li class="itm">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 this
li, the output is as follows:
3. Summary:
target returns the event trigger object
this returns the event binding object
2021 js interview questions and answers (large summary)》
The above is the detailed content of The difference between target and this of event objects in Javascript. For more information, please follow other related articles on the PHP Chinese website!