如何阻止孩子传播由实时/委托侦听器触发的事件?
我有一个委托父级,用于侦听具有特定类别的一组子级中的单击事件。
$(".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 文档,您无法停止实时/委托事件侦听器上的事件传播。
如何阻止 a.toggle 的这些子子级将事件传播给父级?或者在某些情况下可能允许这样做?
您会看到 .toggle
的内部 div 应该是一个下拉菜单。当您单击菜单时,它不应该切换,只有当您单击切换链接时...
I have a delegation parent that listen for click events in a set of children with a specific class.
$(".toggle_group").on("click",".toggle",function(e){ .. });
so heres an example of the 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>
the problem is that children of a.toggle
propogate the event to the parent triggering the handler when it shouldn't. According to jQuery docs you cant stop event propagation on live/delegated event listeners.
How do I stop these sub children of a.toggle from propogating the event to the parent? or maybe in some cases permit it?
You see the inner div of .toggle
is supposed to be a drop down menu. It shouldnt toggle when you click the menu, only when you click the toggle link...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查此页面中的评论,至少有一些声称找到了解决方法。 http://api.jquery.com/event.stopPropagation/
从此处复制了线程的评论备查:
Check the comments in this page, at least some claim to have found workaround. http://api.jquery.com/event.stopPropagation/
Copied the comment from thread here for future reference:
另一种方法是仅当事件来自具有
.toggle
类(或其子级之一)的元素(而不是.toggle_group
元素本身)时才执行函数处理程序。Another approach is to only execute your function handler if the event comes from an element with the
.toggle
class (or one of its children), not the.toggle_group
element itself.