JavaScript Dynamically Add Event Delegates for Events

  • 2021-07-02 23:19:31
  • OfStack

First, let me tell you what event delegation is: Generally speaking, events are onclick, onmouseover, onmouseout, and so on. Delegation is to let others do it. This event was originally added to some elements, but you added it to others to do it and complete this event.

That is, using the bubbling principle, the event is added to the parent to trigger the execution effect.

The so-called dynamic event addition essentially refers 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 the existing element of the current document! However, my friends often encounter a problem, that is, my element is dynamically added to the page later, and I want to bind events to this element. How to deal with it?

To clarify this 1 problem, let's assume that we need to add click events to elements that are later added to the current page.

The core of solving this 1 problem is to use the delegate event of js. The advantage of delegating events is that you can bind events to non-existent elements, and delegating events is often less expensive!

Digression: Take the simplest example: When there are 1000 div on the page, if you bind click events directly to div, it will bind events for 1000 elements. However, if you use event delegates, you only need one element to bind the event. PS: Hopefully it will help you understand the meaning of event delegation.

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

All right, let's get down to business and look at the concrete realization:


//  Simulate dynamic creation of elements li
$.ajax({
type: 'get',
data: {},
success: function () { 
$('<li>').addClass('aaa').html('11111111').appendTo($('body'));
},
});
//  Add an event to the element we just created dynamically 
$(document).on('click', 'li[class=aaa]', function(){
console.log('ddd');
});

Related articles: