点击孩子时没有onclick [英] no onclick when child is clicked
问题描述
我有以下HTML代码:
I have the following html code:
<div class="outerElement">
<div class="text">
Lorem ipsum dolar sit amet
</div>
<div class="attachment">
<!-- Image from youtube video here -->
</div>
</div>
我在.outerElement上有一个jQuery onclick事件但是,我不想要。当我点击附件时要调用的outerElementonclick事件,是否有某种方法可以防止这种情况或检查哪个元素被点击?
And I have a jQuery onclick event on the ".outerElement" however, I dont want the ".outerElement" onclick event to be called when I click on the attachment, is there some way to prevent this or to check which element is clicked?
推荐答案
在子元素上使用 event.stopPropagation()
。
$(".attachment").on("click", function(event){
event.stopPropagation();
console.log( "I was clicked, but my parent will not be." );
});
这可以防止事件将DOM冒泡到父节点。
This prevents the event from bubbling up the DOM to the parent node.
事件
对象的一部分是 目标
成员。这将告诉您哪个元素触发了事件开始。但是,在这种情况下, stopPropagation
似乎是最佳解决方案。
Also part of the event
object is the target
member. This will tell you which element triggered the event to begin with. However, in this instance, stopPropagation
appears to be the best solution.
$(".outerElement").on("click", function(event){
console.log( event.target );
});
这篇关于点击孩子时没有onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!