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 the words can help you understand the meaning of the commissioning of the event.
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('1111111111').appendTo($('body')); },});// Add event $(document).on('click', 'li[class=aaa]', function(){ console.log('ddd');});The above article is a cliché about js dynamic addition events--- Event entrustment is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.