触发子元素的 onclick 事件,而不是父元素的 [英] Trigger child element's onclick event, but not parent's

查看:45
本文介绍了触发子元素的 onclick 事件,而不是父元素的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些嵌套元素,每个元素都有一个 onclick 事件.在大多数情况下,我希望在用户单击子级时触发这两个事件(同时触发父级和子级事件 - 默认行为).但是,至少有一种情况我想触发孩子的 onclick 事件(来自 javascript,而不是用户的点击),而不是父母的.如何防止触发父事件?

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?

我是什么:

用户点击 A: A 的 onclick 触发.
用户点击 B: B 的 onclick 触发,A 的 onclick 也触发
手动触发 B 的点击: B 触发,A 不触发(这是问题所在)

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)

推荐答案

使用 triggerHandler 在孩子身上;这不会让事件通过 DOM 传播:

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

使用 .triggerHandler() 创建的事件不会冒泡 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.

这篇关于触发子元素的 onclick 事件,而不是父元素的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆