简体   繁体   English

* this *优于event.target

[英]Advantage of *this* over event.target

Is it better / faster inside an event listener to use this or event.target 在事件监听器中使用thisevent.target更好/更快

I've been writing code like this (example is jQuery): 我一直在编写这样的代码(例子是jQuery):

jQuery('input').bind('keyup', function (e) {
 var j = jQuery(e.target);
 foo(j.attr('id') , j.val() );
});

And I was told to replace e.target with this because it's "better". 我被告知用this取代e.target ,因为它“更好”。 Is there really any advantage to one or the other? 这个或那个真的有什么优势吗?

I use target because it's a more general solution as it works for delegated events. 我使用target是因为它适用于委派事件,因此它是一种更通用的解决方案。 I'm having trouble benchmarking because my tests get cluttered with the binding (Although, obviously, in this case the difference would be too small to matter anyway) 我在基准测试时遇到了麻烦,因为我的测试结果很混乱(尽管很明显,在这种情况下,差异太小而无关紧要)

The one isn't better than the other, but they do different things: this refers to the element the event is attached to, while event.target is the element that invoked the event. 一个并不比另一个好,但它们做了不同的事情: 是指事件附加到的元素,而event.target是调用事件的元素。

For example 例如

div id=foo   
   div id=bar

when click is attached to foo, and bar is clicked, the event will bubble up to foo. 当click附加到foo并单击bar时,该事件将冒泡到foo。 In the event this will refer to foo and event.target to bar 如果将引用fooevent.targetbar

In the end it depends on which element you need to handle. 最后,它取决于您需要处理的元素。

There's a small example on api.jquery.com/event.target that illustrates event.target. api.jquery.com/event.target上有一个小例子,它说明了event.target。 Here's a small sample that uses that example, but which also displays this : http://jsbin.com/adifan/edit#javascript,html,live 这是一个使用该示例的小样本,但也显示了这个http//jsbin.com/adifan/edit#javascript,html,live

Well, the jQuery documentation is clear about it :-) 那么,jQuery文档很清楚:-)

The target property can be the element that registered for the event or a descendant of it. target属性可以是为事件注册的元素或其后代。 It is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling. 将event.target与此进行比较通常很有用,以确定是否由于事件冒泡而处理了事件。 This property is very useful in event delegation, when events bubble. 当事件冒泡时,此属性在事件委派中非常有用。

(Source: http://api.jquery.com/event.target/ ) (来源: http//api.jquery.com/event.target/

This link explains the term "event bubbling": http://www.quirksmode.org/js/events_order.html 此链接解释了“事件冒泡”一词: http//www.quirksmode.org/js/events_order.html

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

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