jquery - 如何阻止 child 传播由实时/委托(delegate)监听器触发的事件?

标签 jquery events parent-child event-propagation

我有一个委托(delegate)父级,用于监听具有特定类的一组子级中的点击事件。

$(".toggle_group").on("click",".toggle",function(e){ .. });

这是一个 html 示例

<div class='toggle_group'>
  <a class='toggle'>click me and i toggle <div>Im a child of toggle</div></a>
  <a class='toggle'>click me and i toggle <div>Im a child of toggle</div></a>
  <a class='toggle'>click me and i toggle <div>Im a child of toggle</div></a>
  <a class='toggle'>click me and i toggle <div>Im a child of toggle</div></a>
</div>

问题是 a.toggle 的子级将事件传播给父级,在不应该触发处理程序的情况下触发处理程序。根据 jQuery 文档,您无法停止实时/委托(delegate)事件监听器上的事件传播。

如何阻止 a.toggle 的这些子子级将事件传播给父级?或者在某些情况下可能允许这样做?

您会看到 .toggle 的内部 div 应该是一个下拉菜单。当您单击菜单时,它不应该切换,只有当您单击切换链接时...

最佳答案

检查此页面中的评论,至少有一些声称找到了解决方法。 http://api.jquery.com/event.stopPropagation/

复制了此处线程的评论以供将来引用:

MikeW: work around for .live() event propagation issues. nodes created dynamically will not receive the event until after their parent has received it. this will cause funkyness and stopPropagation and preventDefault will not solve this issue. To Fix: add the lines

if(event.target != this){ return true; }

to the top of the parent nodes event handler. this will stop the parent event from firing when the event is actually addressed to a child node, and (unlike return false) will propagate the event to the intended node.

关于jquery - 如何阻止 child 传播由实时/委托(delegate)监听器触发的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9153501/

相关文章:

jQuery 复选框问题

javascript - Jquery 显示隐藏在大屏幕上无法正常工作。并且根本无法在移动设备上工作

c# - 查询事件日志时的越权操作

javascript - 检查是否有任何其他选择具有相同的值集

jQuery 在 p 标签后获取错误的 html() 跨度

java - 如何在 android 中处理 "record"和 "replay"触摸事件?

c# - 在 .NET 中如何检查事件是否已被订阅?

javascript - 从树型对象数组Javascript中获取所有子记录

xml - XML 模式中子元素的命名空间前缀

c++ - 查找父节点在二叉树中的位置