简体   繁体   中英

Advantage of *this* over event.target

Is it better / faster inside an event listener to use this or event.target

I've been writing code like this (example is 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". 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. 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.

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. In the event this will refer to foo and event.target to bar

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. Here's a small sample that uses that example, but which also displays this : http://jsbin.com/adifan/edit#javascript,html,live

Well, the jQuery documentation is clear about it :-)

The target property can be the element that registered for the event or a descendant of it. It is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.

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

This link explains the term "event bubbling": http://www.quirksmode.org/js/events_order.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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