How can I guarantee that JavaScript inserted via AJAX will be executed after the accompanying HTML (also received through AJAX) is ready in the DOM?

I have parts of pages that are replaced with HTML received through AJAX calls. Some of the returned HTML files have JavaScript that needs to be run once to initialize the accompanying HTML (setting up event handlers).

Since the document is already loaded, when I replace HTML chunks with the jQuery .html function, << 21> is not executed because the page loaded long before, and this is just a fragment of the HTML being replaced.

What is the best way to attach event handlers whose code is packed with HTML of interest when this content is loaded via AJAX? Should I just put the javascript procedural block after the HTML, so when I insert a new HTML block, jQuery will execute javascript immediately? Is HTML specifically in the DOM and ready for JavaScript action that is in the same .html call?

+4
source share
2 answers

Some events can be tied to current and future elements using .live () http://api.jquery.com/live/ :

 $('.button').live('click', function() { // do something. }); 

.live () has some limitations (see related documentation):

  • This does not work on native DOM elements like $ ('table'). live ('click', function () {}); will not work.
  • It cannot be chained like $ ('Somediv'). Following(). Live ('click', function () {}); will not work.

Method . delegate () should mitigate these restrictions, but I understand that it has its own limitations. I actually haven't used this one yet ... I don't need to. From the documentation:

A delegate is an alternative to using the .live () method, allowing everyone to associate event delegation to specific DOM elements.

You can also bind new events in the AJAX success / error / complete functions in jQuery:

 $.ajax({ url: 'something.html', success: function(data) { //add new elements with data. //bind new events to elements } }); 
+5
source

jQuery.live exists for this situation.

0
source

Source: https://habr.com/ru/post/1309794/


All Articles