Is there any difference between the following two methods? Is #1 faster than #2 ?
#1
$('#selector').on('click',function(){
$(this)...
// do stuff with clicked element
})
and
#2
$('#selector').on('click',function(e){
$(e.currentTarget)....
// do stuff with clicked element
})
e. target is what triggers the event dispatcher to trigger and e. currentTarget is what you assigned your listener to.
The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.
target is the root element that raised the event. currentTarget is the element handling the event.
Answer. this : this will refer to the context in which the function is called if we use an arrow function, or this will refer to the context in which this is called if we are using a function expression. If we use a function expression we can use this instead of event.
Seems like they are equivalent in most cases, though "this" seems easier to type
according to http://api.jquery.com/event.currentTarget/
event.currentTarget
This property will typically be equal to the
this
of the function.If you are using jQuery.proxy or another form of scope manipulation,
this
will be equal to whatever context you have provided, notevent.currentTarget
In this case, they would do the same thing. But e.currentTarget will always refer to what was clicked on, whereas $(this) will grab the selector you're applying the handler to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With