Causes and solutions of dynamically generated DOM not triggering onclick events

  • 2021-07-09 06:43:25
  • OfStack

Recently, when a friend was doing a project, he encountered dynamic loading of Weibo content, and then clicked "Expand Comments" to get all comments on the Weibo. The dynamically loaded < span mid= '123456789' class= 'get_comment' > Click to load comments < /span > .

And then write


$( " .get_comment).click(function(){

// Response event logic 

})

It is found that click events will not be triggered, and there is no error in listening with console. When you are puzzled,

Because I did in the previous Sohu Home Mall freight management, also encountered, so the focus fell on dynamic loading.

I remember that I used inline events at that time, and I used inline events when loading dynamically. var oBtn = ' < a onclick="Freight.delete_curr_citys();" href="javascript:void(0);" > Delete < /a > '; Freight is actually an object. delete_curr_citys is a method of this object.

Of course, you can also use the live () function of jquery to override the response logic:


$( " .get_comment " ).live( ' click', function() {
var mid = $(this).attr( " mid " );
alert(mid);
});

At this time, jquery can respond to click events of span. The live function is used here to delegate events, which is mainly used to dynamically generate HTML event response. As for the role of live () function, its most intuitive advantage is that it can "listen" to client browser operations directly, and it is also effective for new DOM nodes without rebinding. Perhaps it is because this "monitoring" may be constantly bound and judged, which will cause web application performance problems, and everyone can use it selectively according to the complexity of the project. The live function is explained in great detail here:

Definition and usage

The live () method appends one or more event handlers to the selected element and specifies the function to run when these events occur.

Event handlers attached through the live () method are suitable for matching current and future elements of the selector (such as new elements created by scripts).

Grammar

$(selector).live(event,data,function)

Parameter description

event required. Specifies one or more events attached to an element.

Multiple events are separated by spaces. Must be a valid event.

data is optional. Specifies the extra data passed to the function.

function required. Specifies the function to run when an event occurs.


Related articles: