Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the data attribute of parent element even if the child element is clicked

I'm trying to get the data attribute of a div when clicked in Backbone events(View).

I'm able to achieve this if I click on the div listItem but if I was to click on the child element span it will fail because $(e.target) will be the span.

So how do I get the data attribute of the parent element, even if the child element is clicked?

<div class="listItem" data-showInfo="true">
    <span class="arrow"></span>
</div>

events:{
  "click .listItem": function(e) {

    var $listItem= $(e.target);

    console.log($listItem.data('showInfo'));
  }
}
like image 213
manraj82 Avatar asked Apr 10 '13 11:04

manraj82


2 Answers

Use event.currentTarget instead of event.target, it will be set to the .listItem selector independently of the DOM node you click

var V = Backbone.View.extend({
    events: {
        'click .listItem' : function(e) {
            console.log($(e.currentTarget).data('showinfo'));
        }
    }
});

And a demo http://jsfiddle.net/nikoshr/QyP3Z/

like image 144
nikoshr Avatar answered Nov 15 '22 07:11

nikoshr


You can do it like this:

$('.arrow').click(function(){
alert($(this).parent().attr('data-showInfo'));
});

Your example is in this JSFiddle

like image 26
Debopam Mitra Avatar answered Nov 15 '22 07:11

Debopam Mitra