How do you stop children from propagating an event triggered by a live/delegate listener?

筅森魡賤 提交于 2019-12-07 13:22:49

问题


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


回答1:


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.




回答2:


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.

$(".toggle_group").on("click",".toggle",function(e){
    if (!$(e.target).is(".toggle")) return;

    ...
});


来源:https://stackoverflow.com/questions/9153501/how-do-you-stop-children-from-propagating-an-event-triggered-by-a-live-delegate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!