Event delegation and prevention of bubbling, event delegation to prevent bubbling
Simply put, event delegation and prevention of bubbling
Html:
<Ul class = "clearfix" data-type = "cityPick"> <li class = "active_sort_opts" data-id = "0"> all </li> <li data-id = "88"> New York </li> <li data-id = "119"> Los Angeles </li> <li data-id = "138"> Las Vegas </li> <li data-id = "84"> Hawaii </li> <li data-id = "120"> San Francisco </li> <li data-id = "105"> orlando </li> <li data-id = "118"> Seattle </li> </ul>
Js:
$ ("Ul [data-type = 'citypick']"). on ('click', function () {alert ("parent element ul clicked") ;}); $ ("ul [data-type = 'citypick']"). on ('click', 'lil', function () {alert ("subelement li clicked ");});
When you click a specific li element, we find that the ul event is triggered, which we do not want to see.
Solution:
$ ("Ul [data-type = 'citypick']"). on ('click', function () {alert ("parent element ul clicked") ;}); $ ("ul [data-type = 'citypick']"). on ('click', 'lil', function (e) {e. stopPropagation (); // stop the bubble alert ("sub-element li clicked ");});
Add one sentence to prevent bubbles.
More explanations and excellent articles: http://www.ituring.com.cn/article/467 #
Why does JS block event bubbling?
There is a possibility that a DOM node is bound to an event listener, and the callback function is executed only when the DOM node triggers an event. The result is that an event is triggered by a child node of the node. Due to event bubbling, the DOM node event is also triggered and the callback function is executed, which violates the original intention.
How to prevent javascript event bubbling
1. cancelBubble (html dom Event object attribute): If the Event handle wants to prevent the Event from spreading to an inclusive object, it must be set to true.
2. stopPropagation (html dom Event object method): terminates further propagation of an Event in the capture, target processing, or blister phase of the propagation process. After this method is called, the handler for processing the event on the node will be called, and the event will not be assigned to other nodes.
3. preventDefault (html dom Event object method) notifies the browser not to perform the default action associated with the Event.
Example:
Function stopBubble (e)
{
If (e & e. stopPropagation)
E. stopPropagation ()
Else
Window. event. cancelBubble = true
}
Put this stopBubble (e) function in the function that you want to stop event bubbles to prevent event bubbles.