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

循环中SweetAlert被覆盖?如何让删除按钮与循环项一一对应?

问题分析与解决方案

问题出在两个核心点:一是每个Partial视图重复嵌入事件绑定脚本,导致事件重复绑定;二是SweetAlert回调中错误使用全局选择器,总是选中最后一个匹配的表单提交。

修复步骤:

1. 移除Partial视图中的重复脚本

将Partial视图里的<script>代码完全删除,避免循环渲染时重复绑定事件。修改后的Partial代码:

<td>
    <form asp-action="DeleteActivity" method="post">
        <input type="hidden" name="ActivityID" value="@Model.Activityid" />
        <input name="returnURL" type="hidden" value="@ViewBag.returnURL" />
        <button class="btn ff f-16 background-transparant foreground-red delete-confirm" type="submit" id="@Model.Activityid"> Slet </button>
    </form>
</td>
</tr>

2. 在主视图底部添加单次事件绑定

将脚本移到主视图的表格之后,确保只绑定一次事件,同时在点击时保存当前按钮对应的表单,避免回调中选错目标。

主视图添加的脚本:

<table class="tableView pad-5">
    <!-- 原thead、tbody代码保持不变 -->
</table>

<script type="text/javascript">
    $('.delete-confirm').on('click', function(e) {
        e.preventDefault();
        // 保存当前点击按钮对应的表单,避免回调中全局选择出错
        const targetForm = $(this).closest('form');
        const activityId = $(this).attr("id");

        console.log('DeleteRequest on activityID: ' + activityId);

        swal({
            title: 'Bekræft',
            text: 'Advarsel: Indholdet vil blive permanent slettet!',
            type: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Slet',
            confirmButtonColor: '#C6472A',
            cancelButtonText: 'Fortryd'
        }).then((result) => {
            if (result.value) {
                // 提交预先保存的目标表单
                targetForm.submit();
            }
        });
    });
</script>

可选:更健壮的事件委托写法

如果后续有动态加载的活动项,推荐使用事件委托绑定到父容器,确保新添加的按钮也能触发事件:

$('table.tableView').on('click', '.delete-confirm', function(e) {
    e.preventDefault();
    const targetForm = $(this).closest('form');
    const activityId = $(this).attr("id");

    console.log('DeleteRequest on activityID: ' + activityId);

    swal({
        title: 'Bekræft',
        text: 'Advarsel: Indholdet vil blive permanent slettet!',
        type: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Slet',
        confirmButtonColor: '#C6472A',
        cancelButtonText: 'Fortryd'
    }).then((result) => {
        if (result.value) {
            targetForm.submit();
        }
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:55:19