Another way to handle a common JQuery event handling pattern

Posted by bradgonesurfing on Stack Overflow See other posts from Stack Overflow or by bradgonesurfing
Published on 2011-06-21T13:54:50Z Indexed on 2011/06/21 16:22 UTC
Read the original article Hit count: 132

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery