Paul
Paul

Reputation: 11756

jquery delegate not working with list item

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?

Upvotes: 2

Views: 393

Answers (1)

jfriend00
jfriend00

Reputation: 708146

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_result is a child of #imageTable, you can probably use this instead:

$("#imageTable").delegate(".image_result li", "click", function() {...});

because #imageTable is 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 right li objects.

Upvotes: 4

Related Questions