Javascript does not work on elements added by jquery load (), prepend () or append ()

I have a comment system in which the user submits a comment, the comment is processed, then HTML is returned for the comment. jquery then adds that extracted HTML to the comment system. that the whole system works, but the comment buttons that require javascript do not work unless I refresh the page. How to make my work with javascript on elements added through loading, adding or adding?

Not sure if my question is clear, but here I have javascript:

$(function () { $(".replyform").submit( function (event) { event.preventDefault(); id = $(this).attr("id").split('_')[1]; text = $('textarea#text_'+id).val(); $.post( "/api/add/comment/", {_csrf: _csrf, id: id, text: text, a: a}, function (data) { $('#commentreplies_'+id).prepend(data); $('#replyform_' + id).hide(); }); }); }); 

Then I have elements such as a β€œresponse” for each comment that has functions in external javascript that doesn't work if I don't refresh the page. Hope that made sense.

+4
source share
3 answers

Use jQuery live () (it is deprecated, see on () ) function

+3
source

jQuery has a live method that allows you to add elements that are added to the page after loading to have events already associated with jQuery. You can bind your events using the live method, as described here .

The second solution, and probably more efficient, will use the delegate method to process events with existing containers and delegate them to elements inside this container. Read more about the delegate here .

An example solution using the live method is this: it is assumed that you have buttons with a class response: "

  $(".reply").live('click', function(event) { event.preventDefault(); id = $(this).attr("id").split('_')[1]; text = $('textarea#text_'+id).val(); // post won't work since url is missing, but that code remains the same. // Assuming you get a response like this // <div><input type="textarea" id="text2" /><input type="submit" id="reply_2" value="submitReply" class="reply" /></div> // And if you append this to your document var data = $('<div></div>').html('<input type="textarea" id="text2" /><input type="submit" id="reply_2" value="submitReply" class="reply" />'); $('#commentreplies_'+id).prepend(); $('#reply_' + id).hide(); }); 
+3
source

There are several different approaches to this.

1) Explicitly initialize the button inside the returned HTML for AJAX success

2) Set the global handler for the type of your button using the jQuery live() function (replaced by on() in 1.7)

3) define the button handler in the markup

Which one you choose really depends on your specific task.

+2
source

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


All Articles