![](/img/trans.png)
[英]how can i detect if a parent element has a specific child element with javascript?
[英]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
,此时, this
和event.currentTarget
将引用.parent
元素。但是target
仍将引用origin元素.child
。
$( ".parent" ).click(function(e) {
if ( $( e.target ).hasClass( "child" ) ) {
console.log("child");
}
});
另外,除非您有其他理由要在.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.