Recently, when a friend was working on a project, he encountered dynamically loading Weibo content, and then clicked "Expand Comments" to get all the comments on the Weibo. The dynamically loaded <span mid='123456789' class='get_comment'>click to load comments</span> is used here.
Then write again
$(".get_comment).click(function(){//Response event logic})It is found that the click event will not be triggered, and there is no error in listening using the console. When I can't figure it out,
Because I also encountered it when I was doing freight management at Sohu Home Furnishing Mall, I focused on dynamic loading.
I remember that I was using in-line events at that time, and in-line events when loading dynamically. For example, var oBtn = '<a onclick="Freight.delete_curr_citys();" href="javascript:void(0);">Delete</a>'; In fact, Freight is an object.delete_curr_citys is a method of this object.
Of course, you can also use jquery's live() function to rewrite the response logic:
$(".get_comment").live('click', function() {var mid = $(this).attr("mid");alert(mid);});At this time, jquery can respond to the span click event. Here, live function delegation events are used, which are mainly used for dynamically generated HTML event response. Regarding the role of the live() function, its most intuitive advantage is that it can always "listen" to the client browser operations, which will also be effective for the newly added DOM nodes without rebinding. Perhaps it is because this "listening" may be constantly bound and judged, which will cause web application performance problems. You can selectively use it according to the complexity of the project. Regarding live functions, here is a very detailed explanation:
Definition and usage
The live() method attaches one or more event handlers to the selected element and specifies the functions that run when these events occur.
Event handlers attached via 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 the element.
Multiple events are separated by spaces. Must be a valid event.
data optional. Specifies the additional data passed to the function.
function required. Specifies the function that runs when an event occurs.
The reasons and solutions for the dynamically generated DOM in the above article will not trigger the onclick event are all the content shared by the editor. I hope it can give you a reference and I hope you will support Wulin.com more.