Event bubbling mechanism and event delegation and anonymous function parameters for callbacks

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.