no matter which delete button is clicked?

Please ignore the verbose code; it's a result of trying to figure out
what is going on.

Once this list is loaded, whenever I click on any deleteButton, it
sends a post request with the item id of the last item in the list.
Then the last item is deleted from the database and from the DOM.

The first console.log shows the proper item id, when the click handler
is added. But the second console.log shows the last item id added to
the DOM.

I'm guessing it has something to do with the whole thing about
anonymous functions:

$(document).ready(function() {
    $('#example').click(myfunction(variable));
});

versus

$(document).ready(function() {
    $('#example').click(function() {
        myfunction(variable);
    });
});

but I just don't see it.

-- problem code begin --

$.getJSON("ajax_test.asp", { mode: 'get' } , function(j){
    for (var i = 0; i < j.items.length; i++) {
        var itemID = j.items[i].item_id;
        var itemVal = j.items[i].item;
        var currentItem = '';
        currentItem += '<div id="deleteItemDiv_' + itemID + '">' +
itemVal;
        currentItem += ' <input type="image" src="images/icons/
cancel.gif" id="deleteItemBtn_' + itemID + '" />'
        currentItem += '</div>';
        $('#content p').append(currentItem);
        console.log('Adding click handler for: #deleteItemBtn_' +
itemID);
        var currentDiv = '#deleteItemDiv_' + itemID;
        var currentBtn = '#deleteItemBtn_' + itemID;
        $(currentBtn).click(function() {
            $.ajax({
                beforeSend: function(x) {
                    console.log('Attempting to delete using button: '
+ currentBtn);
                },
                type: 'POST',
                url: 'ajax_test.asp?' + new Date().getTime(), //
prevent caching in IE
                data: {item_id : itemID, mode: 'delete' },
                success: function(msg) {
                    $(currentDiv).remove();
                },
            });

            return false;
        });
    }
});

Thanks much!

-jay

Reply via email to