[英]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.target
和this
,你可能想使用它的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
引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.