Trigger child element's onclick event, but not parent's

妖精的绣舞 提交于 2021-01-27 15:41:30

问题


I've got some nested elements, each with an onclick event. 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. How can I prevent this from triggering the parent event?

enter image description here

What I was is:

User clicks A: A's onclick fires.
User clicks B: B's onclick fires, A's onclick also fires
Manually trigger B's click: B fires, A does not (this one is the problem)


回答1:


Use triggerHandler on the child; this will not let the event propagate through the DOM:

Events created with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.




回答2:


Method 1:

You can use stopPropagation() method to prevent event bubbling.

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

Check out thisDEMO

Method 2:

You can use return false to prevent event bubbling and this will also prevent the default action.

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


来源:https://stackoverflow.com/questions/20505143/trigger-child-elements-onclick-event-but-not-parents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!