jquery deleting a table row help
I开发者_JS百科 have some code like this to delete a row then display a dialog.
the first time i click delete id removes the row straight away. but on any subsequent rows i try to delete i sometimes need multiple clicks before it removes the row.
sometimes the dialog shows and the row is still there!
what is the matter?
EDIT - The db gets updated correctly but the row still remains. its quite erratic sometimes it removes sometimes i have to click twice.
$(".delete-item").click(function () {
var itemId = $(this).attr("id").split('-')[1];
var iType = $(this).attr("id").split('-')[0];
$.post('/User/Delete/', { id: itemId, itemType: iType },function (json) {
if (json.success) {
console.log("#row-"+itemId);
$("#row-"+itemId).hide('slow', function(){ $(this).remove(); });
//$("#dialog-success-delete").dialog("open");
} else {
if(json.error=="unknown"){
$("#dialog-unknown-error").dialog("open");
}
if(json.error=="unauthenticated"){
$("#dialog-unauthenticated").dialog("open");
}
}
});
This could be a timing issue - if the callback for the animation has not happened before another row is clicked, itemId would reference the wrong item.
Change to:
$("#row-"+itemId).hide('slow', function(){ $(this).remove(); });
Since the modal is only sometimes showing, i'm sure there is another problem as well.
There is a note on the post api about silently failing
a request with jQuery.post() returns an error code, it will fail silently unless the script has also called the global .ajaxError()
This would be my best guess, the success callback is never happening because of a server error.
It turned out the problem was I had multiple rows with the same id on the page! I was using tabs and the tables were in separate tabs!.
Verify your selector is correct. Use Chrome, or Firefox + Firebug + Firequery, and console.log($"#row-"+itemId)
where you have the .remove()
. The most likely cause is that itemId does not line up with row ID's like you expect them to.
For starters, you should include the dialog in the function after the hide takes place so it only pops up when the row has been hidden. Second, use the this
selector after you get in. This verifies you're always working on the same row that was initially clicked. Lastly, I don't see a click
method in your code so be sure you're doing it correctly as well.
This code works for me in a quick test:
$("#row-"+itemId).click(function() {
$(this).hide('slow', function() {
$(this).remove();
$("#dialog-success-delete").dialog("open");
});
});
精彩评论