Preventing Propagation of Parent Event Handlers
Consider a tree structure of divs, where clicking on a parent div makes its children invisible. However, clicking on a child div also triggers the parent's click event. To address this issue, we need a way to prevent event propagation up the tree.
One effective approach using jQuery is to add a click handler to the child elements that specifically stops event propagation:
function handler(event) { event.stopPropagation(); // additional code here } $('#a').add('#b').click(handler);
In this code, the stopPropagation() method is used to prevent the event from bubbling up to the parent div. When a click occurs on div '#b', the handler function is invoked, preventing the event from reaching div '#a'. Consequently, the parent's click event is not triggered, preserving the visibility of div '#c'.
The above is the detailed content of How to Stop Event Propagation in jQuery to Prevent Parent Event Handlers from Firing?. For more information, please follow other related articles on the PHP Chinese website!