The difference between
- E.target returns the object (element) that triggered the event
- This returns the object (element) to which the event is bound
code
<div>123</div>
Copy the code
If only one element is bound and there is no nesting, then the output will look the same, right
var div = document.querySelector('div');
div.addEventListener('click', function(e) {
console.log(e.target);
console.log(this);
})
Copy the code
The results
However, if there is nesting, such as this, it is easy to see the difference
<ul>
<li>123</li>
<li>123</li>
<li>123</li>
</ul>
Copy the code
var ul = document.querySelector('ul');
ul.addEventListener('click', function (e) {
console.log(e.target);
console.log(this);
})
Copy the code
The results
In this case, the click event is triggered by clicking on Li, so e.target returns Li; But since this is a UL bound click event, this returns UL.