You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么jQuery的closest().remove()方法在AJAX成功回调中不生效?

问题根因

你遇到的问题是AJAX回调函数的this指向错误:
jQuery AJAX的success回调默认this指向当前AJAX请求的配置对象,不是你绑定submit事件的.removeUserPermission表单元素。你之前测试$(this).closest("tr")不为空,是在外层submit回调的作用域下调试的结果,进入success回调后this指向已经变更,自然无法找到对应表格行执行删除。

修复方案

有三种常用的修复方式,任选其一即可:

方案1:在外层作用域缓存this引用

在进入AJAX请求前先把表单元素的this存为临时变量,回调里直接使用缓存的变量:

$('#userlist').on('submit','.removeUserPermission' ,function(e) {
    e.preventDefault();
    // 缓存当前表单元素的this指向
    const $currentForm = $(this);
    $.ajax({
        type: "post",
        url: "{{ route('role.revokePermission') }}",
        data: $currentForm.serialize(),
        success: function(response) {
            // 直接用缓存的表单元素查找父级tr
            $currentForm.closest("tr").remove();     
        }
    });
});

方案2:使用箭头函数作为回调

箭头函数不会创建自己的this,会继承外层作用域的this指向:

$('#userlist').on('submit','.removeUserPermission' ,function(e) {
    e.preventDefault();
    $.ajax({
        type: "post",
        url: "{{ route('role.revokePermission') }}",
        data: $(this).serialize(),
        // 箭头函数继承外层this
        success: (response) => {
            $(this).closest("tr").remove();     
        }
    });
});

方案3:指定AJAX的context参数

通过jQuery AJAX的context配置项,手动指定回调里的this指向:

$('#userlist').on('submit','.removeUserPermission' ,function(e) {
    e.preventDefault();
    $.ajax({
        type: "post",
        url: "{{ route('role.revokePermission') }}",
        data: $(this).serialize(),
        // 指定回调的this为当前表单元素
        context: this,
        success: function(response) {
            $(this).closest("tr").remove();     
        }
    });
});

内容的提问来源于stack exchange,提问作者Hiddennord

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 23:27:03