i have a form to submit message. I’d like to submit in an AJAX way. the following code works, but the newly add ‘reply’ button doesn’t work:
{% block body %}
<script type="text/javascript" src="{{ url_for('static', filename='jquery.form.js') }}"></script>
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function () {
$("#message_form").ajaxForm(function () {
var messageid = '';
var messagepubdate = 0;
// GET NEWEST MESSAGE ID
$.getJSON($SCRIPT_ROOT + '/_get_new_message', function (data) {
messageid = data.messageid;
messagepubdate = data.messagepubdate;
//alert(messageid); //TESTED! the messageid is the newly added message's _id!
var div = document.createElement("div");
div.innerHTML = "<li><img src='{{ g.get_user(g.user._id).email|gravatar(size=48)}}'><p> " +
"<strong><a href='{{url_for('user_timeline', username=g.user._id)}}'>{{ g.user._id}}</a></strong> " + $('#new_message').val()
+ "<small>— " + messagepubdate + "</small><p align='right' style='text-align: right'><small><a href='#' data-messageid='#replies" + messageid + "' class='reply'>Reply</a></small></p><p><br /><div class='replies hidden' id='replies" + messageid + "'></div></p></p></li>";
$('ul#messages').prepend(div);
});
return false;
});
});
</script>
for old messages, the following scripts works well to toggle the replies div:
<script type=text/javascript>
$(function () {
$('a.reply').click(function () {
messageid = $(this).attr('data-messageid');
$(messageid).text('loading');
$.getJSON($SCRIPT_ROOT + '/_get_replies', { messageid: messageid.substring(8) }, function (data) {
$(messageid).html(data.result);
$(messageid).slideToggle(0);
});
return false;
});
});
</script>
The official jQuery 1.7 answer is
jQuery.on.You can use
jQuery.onto subscribe to any event, and you can usejQuery.offto unsubscribe.To listen to all of the clicks for an element matching
a.reply, regardless of when it was added to the document, you could use the following code:Likewise, you could use
Basically, the
$('body')is the context to which the event listener is added. So in reality, jQuery is waiting for any event to bubble up to thebodyelement, and checking to see if that event is aclickevent. If it is, and the element which gerenated the click event matched thea.replyselector, then jQuery will fire the delegate you passed as the third parameter.If we just did this:
It would work the same way, but only listen to the events generated by the the elements originally selected by the
a.replyselection. Therefore, any new elements added to the dom afterward would not be included. And, because we didn’t add a selector to theonmethod, it will not listen for child events.Edit
In previous versions of jQuery, you would use
jQuery.live, which works in a similar, if not the exact same fashion. In jQuery 1.7,jQuery.livesimply wrapsjQuery.on.