I have a piece of code that loads comments inside a div when the page loads.
$.get("ajax_getcomments.php", { itemid: <? echo $id; ?>, type: 1 },
function(data){
$('#comments').html(data.comment_data);
}, "json");
Inside those results, here is a link attached to each comment
<a href="/ajax_action.php?deletecomment=ID" class="delete_comment"></a>
When that link is pressed, the entire comment div should disappear out of view. I use the following code:
$('.delete_comment').click(function() {
var comment_id = $(this).parent().parent().attr('id');
var objPDiv = $(this).parent().parent();
$.get('./ajax_action.php', {id:comment_id, action: 'delete_comment', ajax: 1}, function(data) {
objPDiv.animate({ opacity: 'hide' }, "slow");
});
return false;
});
The issue is that… it doesn’t work on the html that is fetched from ajax_getcomments.php by jquery.
if I copy/paste the html into the and don’t perform the initial GET call, it works perfectly.
The problem is that
.click()only works for existing elements that match your selector. To bind to future elements, you need to use.live():.live()attaches a handler to the event for all current and future elements that match your selector. So when jQuery sees that you have inserted a new element into the DOM that matches the selector used in.live(), it will automatically attach a handler for theonClickevent to the new element.