简体   繁体   English

Event.target指的是孩子,而不是父母

[英]Event.target refer to the child, not the parent

Consider the following nested div 考虑以下嵌套div

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

In jQuery, I do 在jQuery中,我做到了

$('.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() ? 有没有办法在这种情况下获得对.parent的引用, .parent不是像.closest()

You can use $(this) instead of e.target and this as you may want to use jQuery methods on it. 您可以使用$(this) ,而不是e.targetthis ,你可能想使用它的jQuery方法。

 $('.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. $(this)将始终引用发生事件的元素。

I was confused for a second why I couldn't simply use $(this) reference. 我很困惑,为什么我不能简单地使用$(this)引用。 I am using Meteor which binds this to a different object in an event callback. 我使用Meteor结合this在事件回调到一个不同的对象。 In that case, you can just use event.currentTarget , which I believe how jQuery binds this reference anyway. 在这种情况下,您可以使用event.currentTarget ,我相信jQuery如何绑定this引用。

Just use this , it refers to element on which event has occurred. 只需使用this ,它指的是发生事件的元素。

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

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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