首页 > 解决方案 > 删除成功时从表中删除行?

问题描述

我想从表中删除已删除的行,但它不适用于我。我尝试了以下代码:

场景:当用户单击删除链接/按钮时,它会发送删除请求并从数据库中删除数据,因此它应该更新表前端视图并在成功时删除单击的删除行。

// Delete remedy which is linked with a Symptom ( Symptoms Table )
    $("a.remedy-row-delete").click(function(e) {
        e.preventDefault();

        var remedy_id = $(this).attr('data-id');
        var dataString = '&id='+remedy_id;

        $.SmartMessageBox({
            title: "Delete Remedy",
            content: "Remedy Entry will be deleted, are you sure ?",
            buttons: "[YES][NO]"
        }, function (ButtonPress) {
            if (ButtonPress === "YES"){
                $.ajax({
                    type: 'POST',
                    data: dataString,
                    url: '<?php echo $this->CxHelper->Route('eb-admin-delete-linked-remedy-from-symptom') ?>',
                    success: function(data) {
                        $("#deleteMessage").show().delay(5000).fadeOut();
                        $(this).closest('tr').remove();
                    }
                });
            }
            else {
                $("a.remedy-row-delete").removeClass('alert');
            }
        });
    });

我也尝试过$(this).parent().closest('tr').remove();成功但没有工作。

HTML 标记:

<table id="cx-records-table" class="table display table-striped table-bordered" width="100%">
            <thead>
                <tr>
                    <th>
                        Title
                    </th>
                    <th>
                        Delete
                    </th>
                </tr>
                <?php foreach($remedies as $key => $remedy){ ?>
                    <tr>
                        <td class="all"><?php echo $remedy['title']; ?><br></td>
                        <td><a class="cx-action remedy-row-delete" href="javascript:void(0)" data-id="{{remedy['id']}}"><i class="fa fa-trash-o"></i></a></td>
                    </tr>
                <?php } ?>

            </thead>
            <tbody></tbody>
        </table>

谢谢

标签: javascriptjqueryajaxknockout.js

解决方案


因为函数$(this)内部ajax不同于外部,所以你应该做这样的事情

$("a.remedy-row-delete").click(function(e) {
    e.preventDefault();

    var remedy_id = $(this).attr('data-id');
    var dataString = '&id='+remedy_id;
    var $this = $(this) // <--- 1. Add this line

    $.SmartMessageBox({
        ...
    }, function (ButtonPress) {
        if (ButtonPress === "YES"){
            $.ajax({
                ...
                success: function(data) {
                    ...
                    $this.closest('tr').remove(); // <----change this and will works well
                }
            });
        }
        else {
            $("a.remedy-row-delete").removeClass('alert');
        }
    });
});

推荐阅读