删除在 jQuery 中动态添加的表行



我知道这是一个已经争论过的话题......我已经阅读了有关此的几个主题和答案...但我没有解决问题,所以我需要详细询问我的情况。

我的页面中有一个 html 表,由 AJAX 数据动态填充。 html 表如下:

<table class="table table-borderless table-hover table-centered table-nowrap m-0" id="table_categories">
<thead class="thead-light">
<tr>
<th>Category</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody id="table_tbody">
</tbody>
</table>

tbody 中的行在对数据库进行 AJAX 调用后,使用以下 jQuery 代码动态添加

$.each(data.rows, function(i, item) {
$('#table_categories tbody').append(`<tr><td><h5 class="m-0 font-weight-normal">${item.text}</h5></td><td><span class="badge badge-light-warning">Active</span></td><td><a href="" class="btn btn-xs btn-secondary remove-category" data-id="${item.id}"><i class="mdi mdi-delete"></i></a></td></tr>`);
});

新添加的行将正确绘制到表中。 现在,问题是:如果我单击带有类删除类别的锚点内的 mdi-delete 图标,我想删除相关行。 为此,我使用以下代码。

$("#table_tbody").on("click", ".remove-category", function(e){
e.preventDefault();
let entryId = $(this).data("id");
$.ajax({
url : controller_url + '/remove_category/' + entryId,
type: "GET",
dataType: "JSON"
}).done(function(response){
if(response.status) {
$(this).parents("tr").remove();               
}
});
});

数据已从远程数据库中正确删除...但不会删除表行;我找不到问题。

我可以寻求任何帮助或提示来解决此问题吗? 多谢

$(this)保存在变量中,以便在获得 ajax 响应后可以访问它。

$("#table_tbody").on("click", ".remove-category", function(e){
e.preventDefault();
var $this = $(this); // save $(this)
let entryId = $this.data("id"); //use $this here
$.ajax({
url : controller_url + '/remove_category/' + entryId,
type: "GET",
dataType: "JSON"
}).done(function(response){
if(response.status) {
$this.parents("tr").remove(); // use $this here (again)    
}
});
});

最新更新