gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:49:09 24 4
gpt4 key购买 nike

我有一个委托(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com