简体   繁体   English

触发子元素的onclick事件,但不是父元素

[英]Trigger child element's onclick event, but not parent's

I've got some nested elements, each with an onclick event. 我有一些嵌套元素,每个元素都有一个onclick事件。 In most cases, I want both events to fire when the user clicks the child (both parent and child events are triggered - default behavior). 在大多数情况下,我希望在用户单击子项时触发这两个事件(触发父事件和子事件 - 默认行为)。 However, there is at least one case where I want to trigger the child's onclick event (from javascript, not a user's click), but not the parent's. 但是,至少有一种情况我想触发孩子的onclick事件(来自javascript,而不是用户的点击),而不是父母的。 How can I prevent this from triggering the parent event? 如何防止此事件触发父事件?

在此输入图像描述

What I was is: 我的是:

User clicks A: A's onclick fires. 用户点击A: A的onclick会触发。
User clicks B: B's onclick fires, A's onclick also fires 用户点击B: B的onclick fires,A的onclick也会触发
Manually trigger B's click: B fires, A does not (this one is the problem) 手动触发B的点击: B点火,A点亮(这个是问题)

Use triggerHandler on the child; 对孩子使用triggerHandler ; this will not let the event propagate through the DOM: 这不会让事件通过DOM传播:

Events created with .triggerHandler() do not bubble up the DOM hierarchy; 使用.triggerHandler()创建的事件不会冒泡DOM层次结构; if they are not handled by the target element directly, they do nothing. 如果它们不是直接由目标元素处理的,它们什么都不做。

Method 1: 方法1:

You can use stopPropagation() method to prevent event bubbling. 您可以使用stopPropagation()方法来防止事件冒泡。

$('.element').on('click', function(e){
e.stopPropagation();
});

Check out this DEMO 看看这个DEMO

Method 2: 方法2:

You can use return false to prevent event bubbling and this will also prevent the default action. 您可以使用return false来防止事件冒泡,这也会阻止默认操作。

$('.element').on('click', function(e){
//--do your stuff----
return false;
});

暂无
暂无

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

相关问题 在子元素的onclick事件处理程序中定位父元素 - Target parent element within a child element's onclick event hander 如何仅在子 div 元素中而不在父 div 中触发 onclick 事件? - How to trigger onclick event only in the child div element but not in the parent div? 为什么子元素属性传递给父元素<tr>元素的 onClick 事件(反应)? - Why are child element properties passed into parent <tr> element's onClick event (React)? 如何使父级事件在单击子元素时不会触发,但不会阻止子元素事件 - How to get a parent's event to not trigger when clicking on child elements, but not prevent child element events 当孩子的 onClick 被触发时触发向父级注册的 onKeyUp 事件 - Firing onKeyUp event registered with parent when child's onClick is fired 子 div 上的 OnClick 不应触发特定子级的父 div 的 onClick 方法 - OnClick on child div should not trigger parent div's onClick method for a particular child 如何通过其父级触发子级 object 上的 hover 事件? - How to trigger hover event on child's object via its parent? 单击事件目标给出元素或其子元素,而不是父元素 - Click event target gives element or it's child, not parent element 父子元素的独立onClick事件 - Separate onClick event for parent and child element 在React中,如何在父元素内的子元素中测试click事件 - In React, how to test the click event in child that's inside a parent element
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM