admin管理员组

文章数量:1201370

I'm starting to lose my mind with Jquery today, I lookep up the other questions but nothing worked so far. I have the simple html structure (added dynamically in a for loop).

<div id="cell'+i+'" class="cell emptyCell">
     <div class="handle"></div>
     <div class="content"></div>
</div>

I'm using the "on" method to bind the "click event" of elements of class ".emptyCell" with a custom function.

$(document).on('click','.emptyCell', function(e){

    console.log(e.target.id);

});

But when the user clicks on the .content div (child of emptyCell), it catches the event, and the console prints "undefined" since .content elements don't have ids here.

How is that even possible ? Isn't the .on function supposed to bind elements of class .emptyCell only ?

Thanks for your help

I'm starting to lose my mind with Jquery today, I lookep up the other questions but nothing worked so far. I have the simple html structure (added dynamically in a for loop).

<div id="cell'+i+'" class="cell emptyCell">
     <div class="handle"></div>
     <div class="content"></div>
</div>

I'm using the "on" method to bind the "click event" of elements of class ".emptyCell" with a custom function.

$(document).on('click','.emptyCell', function(e){

    console.log(e.target.id);

});

But when the user clicks on the .content div (child of emptyCell), it catches the event, and the console prints "undefined" since .content elements don't have ids here.

How is that even possible ? Isn't the .on function supposed to bind elements of class .emptyCell only ?

Thanks for your help

Share Improve this question asked Oct 18, 2013 at 16:39 webabawebaba 6515 silver badges17 bronze badges 1
  • I don't think so, I think it's because they overlapping, and target refers to the initial event as expalined in the answer – webaba Commented Oct 18, 2013 at 16:51
Add a comment  | 

1 Answer 1

Reset to default 27

e.target refers to the actual element where the click happened(it can be handle or content elements), if you want to refer emptyCell then you can use this or e.currentTarget

$(document).on('click','.emptyCell', function(e){
    console.log(this.id);
    console.log(e.currentTarget.id);
});

Demo: Fiddle

本文标签: javascriptJquery click event on selector returns child as targetStack Overflow