如何通过单击父元素来检测子元素?

时间:2018-01-11 15:46:02

标签: javascript jquery dom-events

我有一个parent元素的点击功能。我想现在检测我点击的部分是否有#34;孩子"



 
$( ".parent" ).click(function() {
    if ( $( this ).hasClass( "child" ) ) {
        console.log("child");
    }   
});

.child{background-color:pink}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


 <table style="width:100%">
  <tr class="parent">
    <th>Firstname</th>
    <th>Lastname</th>
    <th class="child">Age</th>
  </tr>
</table> 
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

访问event.target,这始终引用创建事件的原始目标。

在这种情况下,事件以.child开始,并冒泡到.parent,这会触及此聆听者......此时,thisevent.currentTarget将引用.parent元素..但target仍会引用原始元素.child

$( ".parent" ).click(function(e) {
    if ( $( e.target ).hasClass( "child" ) ) {
        console.log("child");
    }   
});

JSFiddle Demo

此外,除非你有其他理由让{1}}上的听众,你可以直接将听众添加到孩子:

.parent

答案 1 :(得分:2)

您可以使用event.target来确定点击的原始目标:

&#13;
&#13;
$(".parent").click(function(e) {
  if ($(e.target).hasClass("child")) {
    console.log("child");
  }
});
&#13;
.child {
  background-color: pink
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table style="width:100%">
  <tr class="parent">
    <th>Firstname</th>
    <th>Lastname</th>
    <th class="child">Age</th>
  </tr>
</table>
&#13;
&#13;
&#13;

相关问题