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

使用SweetAlert自定义删除确认时待删除数据名称显示undefined如何解决

问题原因

显示undefined是两个核心错误导致:

  • 通过onclick属性直接调用函数时,函数内部的this默认指向全局window对象,不是你点击的按钮元素,所以$(this).data("name")无法拿到预期值
  • 你的按钮标签上没有添加存储分类名称的data-name自定义属性,就算this指向正确也取不到对应的值
  • 另外你代码还存在一个隐藏问题:表单的ID是DeleteCategory + id,但提交时写的是DeleteService + id,会导致找不到目标表单,也需要同步修复

修复步骤

1. 修改按钮与表单代码

给按钮新增data-name属性存储分类名,同时在调用deleteCategory时把当前按钮元素作为第二个参数传入:

<button type="submit" onclick="deleteCategory('{{ $categories->id }}', this)" data-name="{{ $categories->name }}" class="dropdown-item text-danger" href="#">
  <i class='bx bxs-trash-alt' ></i> 删除
</button>
<form action="{{ route('categories.destroy', $categories->id) }}" method="post" id="DeleteCategory{{ $categories->id }}">
    @csrf
    @method('delete')
</form>

2. 修改JS逻辑代码

调整函数接收按钮元素参数,修正表单ID的拼写错误:

<script>
function deleteCategory(id, el) {
    // 从传入的按钮元素获取分类名
    var name = $(el).data("name");
    var content = document.createElement('div');
    content.innerHTML = '删除 <strong>'+ name + '</strong> 分类时会同时删除其下所有子分类。';
    Swal.fire({
        title: '你确定吗?',
        html: content,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: '确认删除',
        cancelButtonText: '取消'
    })
    .then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: "正在删除",
                showConfirmButton: false,
                timer: 2300,
                timerProgressBar: true,
                onOpen: () => {
                    // 修正表单ID的拼写错误
                    document.getElementById(`DeleteCategory${id}`).submit();
                    Swal.fire(
                    '删除成功!',
                    '分类已成功删除',
                    'success'
                    )
                }
            });
        }
    })
}
</script>

如果需要保留原来的印尼语提示,只替换核心逻辑部分即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 15:51:02