简体   繁体   English

当我只能使用元素本身时,为什么还要使用 event.currentTarget?

[英]Why use event.currentTarget when I can just use the element itself?

Say I want to add rounded-circle class to an image when I click on it:假设我想在单击图像时将rounded-circle class 添加到图像中:

const img = document.getElementById('my-image');
img.addEventListener('click', () => {
  event.currentTarget.classList.add('rounded-circle');
});

I've been taught to use event.currentTarget in order to select that image within the callback.我被教导使用event.currentTarget以便在回调中 select 该图像。 However, since this image is already declared in the variable img , I can also do:但是,由于该图像已经在变量img中声明,我也可以这样做:

const img = document.getElementById('my-image');
img.addEventListener('click', () => {
  img.classList.add('rounded-circle');
});

So why use event.currentTaget instead of img ?那么为什么要使用event.currentTaget而不是img呢? Is there a preferred way, and why?有没有首选的方法,为什么?

The currentTarget returns the element whose event listener triggered the event. currentTarget 返回其事件侦听器触发事件的元素。 in contrast to target which returns the element triggered the event.与返回元素触发事件的目标相反。 Another way to get the element whose event lsitener triggered, is through this keyword in event listener:获取事件 lsitener 触发的元素的另一种方法是通过事件侦听器中的this关键字:

document.getElementById('my-image').addEventListener('click', function () => {
  this.classList.add('rounded-circle');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM