【问题标题】:Delete table row dynamically added in jQuery删除jQuery中动态添加的表行
【发布时间】:2020-10-02 02:13:44
【问题描述】:

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

我的页面中有一个 html 表格,由 AJAX 数据动态填充。 Tha 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>

在对数据库进行 AJAX 调用之后,tbody 中的行通过以下 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>`);
});

新添加的行已正确绘制到表格中。 现在,问题是:如果我单击带有类 remove-category 的锚内的 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();               
        }
    });
});

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

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

【问题讨论】:

    标签: jquery ajax html-table


    【解决方案1】:

    $(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)    
            }
        });
    });
    

    【讨论】:

    • 非常感谢克隆...它解决了这个问题。我能问一下原因吗?我想了解和了解更多关于 javascript/jQuery
    • 我不能在这里很好地解释它,只是为了给你指出正确的方向:这在 JS 中并不总是你所期望的。谷歌搜索 this JavaScript explained 之类的东西,以便从在这个网站上拥有多个像我这样的角色的人那里得到很好的解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 2017-04-05
    • 2016-02-07
    • 1970-01-01
    • 2015-09-26
    • 2016-10-29
    相关资源
    最近更新 更多