最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Event.target refer to the child, not the parent - Stack Overflow

programmeradmin2浏览0评论

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()?

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()?

Share Improve this question asked Jul 22, 2015 at 6:42 Maximus SMaximus S 11.1k19 gold badges80 silver badges163 bronze badges 2
  • I don't think so!! See this fiddle. More understandable Fiddle – Guruprasad J Rao Commented Jul 22, 2015 at 6:44
  • 1 I was so spoiled by jQuery's this that I forgot about event.currentTarget – Maximus S Commented Jul 22, 2015 at 7:04
Add a ment  | 

3 Answers 3

Reset to default 4

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./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

发布评论

评论列表(0)

  1. 暂无评论