简体   繁体   中英

Event.target refer to the child, not the parent

Consider the following nested div

<div class="parent">
  <div class="child"></div>
</div>

In jQuery, I do

$('.parent').click(function (e) {
  e.target // this refers to .child instead of .parent
})

Is there a way to get the reference to .parent in this case withut doing something like .closest() ?

You can use $(this) instead of e.target and this as you may want to use jQuery methods on it.

 $('.parent').click(function(e) { alert($(this).attr('class')); }); 
 .parent { color: green; } .child { color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <div class="parent"> Parent <div class="child">Clild</div> </div> 

$(this) will always refer to the element on which the event has occurred.

I was confused for a second why I couldn't simply use $(this) reference. I am using Meteor which binds this to a different object in an event callback. In that case, you can just use event.currentTarget , which I believe how jQuery binds this reference anyway.

Just use this , it refers to element on which event has occurred.

$('.parent').click(function (e) {
    console.log(this);
})

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM