开发者

After removing <tr> from table with jquery, wrong functions are called on click events for buttons in other rows

The setup is the following: each row in the table describes an item from database, according to a specific form. Each <td> element represents a value of a form element. The first <td> element in each row is a button which on click is supposed to send to the server the item_id held in its (the button's) row and after the server returns success, the row containing the id that was sent is supposed to be removed.

What actually happens, is that after I remove some row, later in the onclick function in other rows the id is the one of the removed row. For example if I have:

<tr id=1></tr>
<tr id=2></tr>

Jquery code used to remove rows: (itemId is changed in loop...)

var num = 开发者_运维技巧eval($("#oldnum").val()) + 2;
for (var i=2; i < num; i++ ){
//      var remElem = $('#items tbody tr:nth-child('+i+') img[name="remitem"]');
        var remElem = $('#remitem'+(i-2));
        var row = $('#items tbody tr:nth-child('+i+')');
        var itemId = $(row).attr('id').split("_");
        //id of a row is item_actualId, we want the actualId
        itemId = itemId[1];
        $(remElem).click(function(){
            removeExistingItem(itemId);
        });
}
...
function removeExistingItem(itemId){
    var answer = confirm("האם ברצונך למחוק את  הפריט?");
    if (!answer){
        return;
    }
    var path = window.location.pathname;
    $.ajax({
        url: "/po/removeitem", dataType: "json",
        data: {id: itemId, format: "json"}, success: function(){
            $('#items tr[id="item_'+itemId+'"]').remove();
        }
    });
}

Any help is welcomed...


I think you can simplify this by simply maintaining your reference:

$(remElement).click(function()
{
    var currentObj = this;

    $.ajax({
       url: 'myUrl',
       data: { myData: 'Value1' },
       success: function()
       {
           $(currentObj).parent().parent().remove();
       }
    });
});

Simply maintain a reference to your current object, and then walk up the tree to find it's parent row and remove that.


Why don't you try doing: (using the id selector)

$('#item_'+itemId).remove();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜