Another way to handle a common JQuery event handling pattern
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
ev开发者_如何转开发ents:
"click a.foo": "editLogItem"
editLogItem: (e)->
t = $(e.target).closest("a")
Example
$(this)
will get the element defined by the selector you bind too.
$("a.foo").click(function (e){
var data = $(this).data("info");
});
You should also use .data
rather then .attr("data-...")
Edit:
If this
is overwritten you can use e.currentTarget
which will have the same value.
If the handler is attached to the <a>
anyway, that'll always be this
in the handler, so it doesn't matter what the target was.
$("a.foo").click(function (e){
var data = $(this).data('info');
// ...
});
Note also that to get the value of "data-xxx" attributes you can use the ".data()" function.
$('a.foo').click(function () {
var data = $(this).data('info');
});
I'm using the click handler because you specifically mention catching the click event.
精彩评论