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

Laravel 9:SweetAlert2删除确认弹窗提前消失直接删数据问题排查

问题分析与解决方案

问题原因

  1. <a>标签点击后会立即触发默认跳转行为(访问href指定的删除路由),导致SweetAlert弹窗被页面跳转中断,同时直接执行了删除操作,完全跳过了确认流程。
  2. 函数参数名formId与全局变量formId重名,存在变量覆盖的风险,属于不良编码实践。
  3. SweetAlert2的type参数已被废弃,无需重复设置(已通过icon指定弹窗类型)。

修复步骤

1. 修改<a>标签代码

更新onclick事件,传递事件对象并返回函数结果,阻止默认跳转:

<a  href="{{ route('data-entry.lost-and-found.destroy', $lostFound) }}"
    onclick="return deleteConfirm(event)"
    data-id="{{ $lostFound->id }}"
    data-toggle="tooltip"
    class="dropdown-item px-3 btn btn-sm btn-outline-danger btn-active-light-danger">
       Delete
</a>

2. 修正SweetAlert2函数代码

  • 阻止事件默认行为
  • 修正变量名冲突
  • 移除废弃参数
<script>
    const deleteForm = document.getElementById('LFform');

    window.deleteConfirm = function(event) {
        // 阻止a标签的默认跳转行为
        event.preventDefault();
        
        Swal.fire({
            icon: 'warning',
            text: 'Are you sure you want to delete this?',
            showCancelButton: true,
            confirmButtonText: 'Delete',
            confirmButtonColor: '#e3342f',
            dangerMode: true,
        }).then((result) => {
            if (result.isConfirmed) {
                deleteForm.submit();
            }
        });
        
        return false;
    }
</script>

补充说明(多删除项场景)

如果页面存在多个删除按钮,每个按钮对应独立表单,可通过data-id关联表单:

  • 表单设置ID:<form id="LFform-{{ $lostFound->id }}" ...>
  • 修改JS函数,通过事件目标获取data-id并匹配表单:
window.deleteConfirm = function(event) {
    event.preventDefault();
    const itemId = event.target.dataset.id;
    const deleteForm = document.getElementById(`LFform-${itemId}`);
    
    Swal.fire({
        // 弹窗配置不变
    }).then((result) => {
        if (result.isConfirmed) {
            deleteForm.submit();
        }
    });
    
    return false;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:15:32