Its so-called dynamic Add event essence refers to the event delegation in JS.
We know that in JS, event handling can only be bound to the currently selected element, in other words, event processing can only be bound to the existing elements of 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 want to give the element binding events, how to deal with?
To illustrate the white issue, we assume that you need to add the click event to the element that you later add 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 elements that do not exist, and delegate events tend to cost less!
digression: Give the simplest example: when there are 1000 div on the page, if the div is directly bound to the Click event, it will bind the event to 1000 elements. However, if you use an event delegate, you need only one element binding event. PS: I hope it will let you understand the meaning of the event delegate.
We just want to know how dynamically created elements add events, you say so much to do, what to do ...
All right, let's go to the details:
Simulate dynamic creation element Li
$.ajax ({
type: ' Get ',
data: {},
success:function () {
$ (' <li> '). AddClass (' AAA '). HTML (' 11111111 '). Appendto ($ (' body ');
},
});
Add event $ (document) to the element we just created dynamically
. On (' Click ', ' li[class=aaa] ', function () {
console.log (' ddd ');
});
The above Cliché JS Dynamic Add Event---Event delegate is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.