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

Laravel+DataTables项目用SweetAlert2时点击取消仍删数据的原因?

问题排查与解决办法

嘿,这个问题我之前也碰到过!核心原因很简单:你没有阻止删除按钮的默认行为——不管你点弹窗的确认还是取消,原来的删除请求(跳转链接或表单提交)已经自动触发了,所以数据都会被删掉。

我给你分两种场景说具体的解决办法,适配Laravel+DataTables的常见情况:

场景1:用<a>标签做删除按钮

如果你是用带href的a标签做删除按钮,原来的代码大概率是直接绑定点击事件,但没阻止跳转。改成这样:

// 注意:如果是DataTables动态生成的按钮,要用事件委托(绑定到document)
$(document).on('click', '.delete-btn', function(e) {
    // 第一步:阻止a标签的默认跳转行为
    e.preventDefault();
    // 保存删除地址
    const deleteUrl = $(this).attr('href');

    Swal.fire({
        title: '确定要删除吗?',
        text: '删除后数据无法恢复哦!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: '是的,删除!',
        cancelButtonText: '取消'
    }).then((result) => {
        // 只有用户点击确认时,才执行删除跳转
        if (result.isConfirmed) {
            window.location.href = deleteUrl;
        }
    });
});

场景2:用表单提交删除(Laravel推荐方式)

如果是用表单包裹删除按钮(符合Laravel的CSRF和请求规范),要阻止表单的默认提交,确认后再手动提交:

// 同样,动态生成的表单用事件委托
$(document).on('submit', '.delete-form', function(e) {
    // 阻止表单默认提交
    e.preventDefault();
    const deleteForm = this;

    Swal.fire({
        title: '确定要删除吗?',
        text: '删除后数据无法恢复哦!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: '是的,删除!',
        cancelButtonText: '取消'
    }).then((result) => {
        if (result.isConfirmed) {
            // 确认后手动提交表单
            deleteForm.submit();
        }
    });
});

关键提醒

因为DataTables是动态渲染表格内容的,所以不能直接用$('.delete-btn').click()绑定事件,必须用事件委托(绑定到document或父容器),否则动态生成的按钮会绑定不上事件。

这样修改后,点击取消按钮时,就不会触发任何删除操作了,只有确认后才会执行删除请求~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:15:53