3

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

在此处输入图像描述

我的情况是:

用户点击 A: A 的 onclick 触发。
用户点击 B: B 的 onclick 触发,A 的 onclick 也触发
手动触发 B 的点击: B 触发,A 没有(这个是问题)

4

2 回答 2

4

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.

于 2013-12-10T21:10:08.697 回答
3

方法一:

您可以使用 stopPropagation()方法来防止事件冒泡。

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

看看这个DEMO

方法二:

您可以使用它 return false来防止事件冒泡,这也将阻止默认操作。

$('.element').on('click', function(e){
//--do your stuff----
return false;
});
于 2016-07-27T08:53:15.493 回答