1. Event bubbling mechanism:
The event bubbling mechanism is that when an event is bound to an element, if the element does not exist or if the callback function returns ture, the event will bubble up and continue to bind the element's parent element until document. (If the event returns false, it does not bubble)
Block bubbling: 1. Event return false; 2.evt.stoppropagation (this evt refers to this event, written in the parameters of the event anonymous callback function) For example: $ (' Li '). Click (function (evt) {evt.stoppropagation ()});
2. Event Delegation:
Both the on method and the delegate method of jquery can be used to bind events to future elements, and the principle is to use event bubbling mechanism
The on method and the delegate method bind the event handler (delegate) to the parent element of the element that needs to be bound, and when its child elements trigger an event, the event bubbles up to trigger the "event handler" on the parent element, which in turn determines whether the element in which the event occurred is a child element. If it is not a child element, the event handler function is not executed;
The specific idea is the following:
// Gets the parent node and adds a click event document.getElementById ("Parent-list") to it. AddEventListener ("click",function (e) { // Check if event source E.targe is Li if(E.target && E.target.nodename.touppercase = = "LI") {// The real process is here console.log ("List Item ", E.target.id.replace (" post-")," was clicked! " ); }});
E is the element/event source for this event, the E.target event;
Event bubbling mechanism and event delegation and anonymous function parameters for callbacks