JS Dynamic Add Event-event delegate

Source: Internet
Author: User

White Wolf Source: http://www.manks.top/javascript-dynamic-event.html This article copyright belongs to the author, welcome reprint, but without the author's consent must retain this paragraph statement, and in the article page obvious location gives the original text connection, Otherwise, the right to pursue legal liability is retained.

Its so-called dynamic add event is essentially referring to the event delegate in JS.

We know that in JS, event handling can only be bound to the currently selected element, in other words, event handling can only be bound to elements that already exist in the current document! However, often the small partners will encounter a problem is that my element is later dynamically added to the page, and I would like to bind the element to the event, how to deal with it?

To illustrate the problem of white, we assume that the Click event needs to be added to the element that is added to the current page.

The core of solving this problem is to use JS's delegate event. The advantage of delegating events is that you can bind events to non-existent elements, and delegate events tend to be less expensive!

Aside: one of the simplest examples: when you have 1000 div on the page, if you directly bind the click event to the Div, it will bind the event to 1000 elements. However, if you use an event delegate, you only need an element binding event. PS: I hope that you can understand the meaning of the event delegate.

We just want to know how dynamically created elements add events, what you say so much to do, what to do ...

Well, let's go to the concrete realization:

// simulate dynamic creation of elements Li $.ajax ({    ' get ',    data: {},    function  () {                        $ (' <li> '). AddClass (' AAA '). HTML (' 11111111 '). AppendTo ($ (' body '));    }); // to add an event for the element we just created dynamically function () {    console.log (' ddd ');});

View Original

JS Dynamic Add Event-event delegate

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.