Let me first tell you what event commission is: In layman's terms, events are onclick, onmouseover, onmouseout, etc., etc. are events. As for delegation, it is to let others do it. This event is originally added to certain elements, but you add it to others to do it to complete the event.
That is: use the principle of bubbles to add events to the parent to trigger the execution effect.
The so-called dynamic event addition essentially refers to event delegation in js.
We know that in js, event processing can only be bound to the currently selected element, in other words, event processing can only be bound to the elements that already exist in the current document! However, often friends will encounter a problem that my element was dynamically added to the page later, and I want to bind events to the element. How to deal with it?
To illustrate this problem, we assume that we need to add a click event to the elements that are later added to the current page.
The core of solving this problem is to use the delegate event of js. The advantage of delegated events is that they can bind events to non-existent elements, and delegated events often have smaller overheads!
Off topic: Let me give you the simplest example: When there are 1000 divs on the page, if the div is directly bound to the click event, it will be 1000 element-bound events. However, if you use event delegate, you only need one element to bind the event. PS: I hope that the long-winded words will help you understand the meaning of the event delegation.
We just want to know how dynamically created elements add events, what do you say so much to do, what do...
OK, let's get back to the point, see the specific implementation:
// Simulate dynamic creation of element li$.ajax({ type: 'get', data: {}, success: function () { $('<li>').addClass('aaa').html('11111111').appendTo($('body')); }, }); // Add events to the elements we just created dynamically$(document).on('click', 'li[class=aaa]', function(){ ('ddd'); });
The above is the JavaScript dynamic addition event commission introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!