[英]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.
如果它们不是直接由目标元素处理的,它们什么都不做。
You can use stopPropagation()
method to prevent event bubbling. 您可以使用
stopPropagation()
方法来防止事件冒泡。
$('.element').on('click', function(e){
e.stopPropagation();
});
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.