繁体   English   中英

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

[英]How can I detect a child element by clicking on a parent element?

我有一个parent元素的点击功能。 我现在要检测我单击的部分是否具有“子级”类

 $( ".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> 

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

在这种情况下,事件以.child开始,然后冒泡直到到达此监听器的.parent ,此时, thisevent.currentTarget将引用.parent元素。但是target仍将引用origin元素.child

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

JSFiddle演示

另外,除非您有其他理由要在.parent上使用侦听.parent ,否则可以将侦听器直接添加到子级,如下所示:

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

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

 $(".parent").click(function(e) { if ($(e.target).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> 

暂无
暂无

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

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