I’m using an older version of jquery (1.6.2) and can’t seem to get delegate working. I have a list that I’m trying to use delegate on a click event but it fails after the list is reloaded.
Here is my current code:
$(".image_result").delegate("li", "click", function() {
//$('.image_result li').click(function() {
var imgInfo = $(this).attr('id').split(':');
if(confirm('Are you sure you want to delete this image?')) {
$.post('delete_image.php?image_id=' + imgInfo[0] + '&user_id=' + imgInfo[1], function(data) {
if (data.st) {
var resp = data.html.split("|");
$('#imageStats').html(resp[0]);
$('#imageTable').html(resp[1]);
}
else {
alert("Yikes, something went wrong");
}
}, "json");
}
});
The imageTable div now holds the new list items (image_result)
What am I missing?
The key to
.delegate()is that you cannot destroy/replace the item in the jQuery object (in this case.image_result. Doing so, kills your jQuery event handler. The selector you use in the jQuery object must be static (not getting destroyed or replaced).In your case and assuming that
.image_resultis a child of#imageTable, you can probably use this instead:because
#imageTableis not getting replaced so it’s event handler survives changes to the child objects and the selector passed as an argument to.delegate()zeroes in on the rightliobjects.