I have the following code for example
$("a.foo").bind(function (e){
var t;
if ( $(e.target).is("a") ){
t = $(e.target);
}else{
t = $(e.target).parent("a");
}
var data = t.attr("data-info");
});
In english. I might have a list of anchors within which there may be
a number of spans. Each anchor is declared as
<a class="foo" href="#" data-info="1">
<span> ... </span>
<span> ... </span>
</a>
<a class="foo" href="#" data-info="2">
<span> ... </span>
<span> ... </span>
</a>
...
...
I bind a handler to the click event of the anchor
but the event object comes back with the anchor OR one of the spans
depending on where I click. So to get my html5 “data-info” value into
the callback I have to insert a bit of messy code. This is now appearing
throughout my code to the point where I am guessing there might be an
idiomatic JQuery way of handling this.
EDIT: Backbone snippet showing my real problem ( excuse the coffeescript )
class DashboardView extends Backbone.View
events:
"click a.foo": "editLogItem"
editLogItem: (e)->
t = $(e.target).closest("a")
Example
$(this)will get the element defined by the selector you bind too.You should also use
.datarather then.attr("data-...")Edit:
If
thisis overwritten you can usee.currentTargetwhich will have the same value.