我在表格中的每一行都有一个删除按钮。在ajax调用成功完成后,tr
应该从DOM中删除。
在$.ajax
部分之前,我定义变量var $row = $(this).closest('tr')
并在ajax内部确认我有正确的行。
在$.ajax
内,我有这个:
success: function(response) {
if(response.success == 1) {
alert('success');
if(typeof $row == 'undefined' ) {
alert('undefined!'); // this alert does not come up
} else {
alert('the $row var is defined'); // this alert DOES come up
$row.html('hahaha'); // this works, the contents of the row are replaced
$row.remove(); // this doesn't work. The row is still there, with 'hahaha'
}
} else {
alert('failed');
}
}
这怎么可能?我不允许删除基于它调用的脚本内的一行吗?
这是完整的代码。我让它立即隐藏行,然后如果ajax成功则删除,如果失败则再次显示它。 remove()
不起作用,无论我是否先hide()
。
$(document).on("click",".allowed_val_delete",function() { // 20150328
var $this_row = $(this).closest('tr');
var allowed_val_id = $this_row.attr("id").split('_')[1];
var data = new Object();
//alert('Delete allowed value with id "' + allowed_val_id + '"');
data.action = 'DELETE';
data.id = parseInt(allowed_val_id,10);
$this_row.hide(); // hide row immediately. Show it again if ajax fails.
$.ajax({
data: data,
//type: "POST",
type: "POST", // 20150502 experimenting with other HTTP methods. (method is alias for type but requies jquery 1.9+)
url: "controllers/core_fields/ajax/allowed_values.php",
dataType: "json",
success: function(response) {
if(response.success == 1) {
//alert('Removing row');
if(typeof $this_row == 'undefined') {
alert('$this_row with val_id = ' + allowed_val_id + ' is undefined');
} else {
//alert('$this_row with val_id = ' + allowed_val_id + ' is defined');
$this_row.remove(); // doesn't work
}
/*var index = allowed_value_ids.indexOf(allowed_val_id);
allowed_value_ids.splice(index,1); // remove from the list of ids*/
$("#maintable").tablesorter().trigger("update"); // updates sorting
$("#maintable").tablesorter().trigger("appendCache"); // updates sorting
} else {
alert('Failed to remove');
$this_row.show();
}
//alert('action: ' + response.action + '; id: ' + response.id);
//alert(response);
}
});
});