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