如何阻止儿童传播由直播/代理听众触发的活动? [英] How do you stop children from propagating an event triggered by a live/delegate listener?

查看:103
本文介绍了如何阻止儿童传播由直播/代理听众触发的活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

所以,一个html的例子

 < div class ='toggle_group'> 
< a class ='toggle'>点击我,我切换< div> Im是一个孩子的切换< / div>< / a>
< a class ='toggle'>点击我,我切换< div> Im是一个孩子的切换< / div>< / a>
< a class ='toggle'>点击我,我切换< div> Im是一个孩子的切换< / div>< / a>
< a class ='toggle'>点击我,我切换< div> Im是一个孩子的切换< / div>< / a>
< / div>

问题是 a.toggle 将事件传播给父级,当它不应该触发处理程序。根据jQuery文档,您不能阻止活动/委托事件监听器上的事件传播。



如何阻止这些子项目的传播给父母?或者在某些情况下允许它?



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

解决方案

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



将线程的注释复制以备将来参考:


MikeW:
.live()事件传播问题。节点创建
动态将不会收到事件,直到他们的父项
收到它。这将导致时髦和stopPropagation和
preventDefault不会解决这个问题。修复:添加行



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



到父节点事件处理程序的顶部。当事件实际寻址到
子节点时,这将阻止
父事件触发,并且(不同于return false)将将事件传播到
目标节点。



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...

解决方案

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:

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.

这篇关于如何阻止儿童传播由直播/代理听众触发的活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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