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

如何避免删除确认弹窗点击取消后触发多次误删?

问题分析与解决方案

这个问题我太熟了,本质是事件重复绑定在搞鬼!

为什么会同时删除两条记录?

每次你点击删除按钮(.delete_item)的时候,代码都会给确认按钮(.confirmation)新增一个点击事件处理函数——但之前绑定的事件并没有被清除!比如:

  1. 点击ID1的删除按钮,绑定了一个用ID1的user_id发请求的事件;
  2. 点取消后,这个事件还留在确认按钮上;
  3. 再点击ID2的删除按钮,又绑定了一个用ID2的user_id的事件;
  4. 此时点确认,两个事件会同时执行,自然就把ID1和ID2都删了。

两种靠谱的解决方案

方案1:用.one()绑定确认事件(最简单)

.one()方法会确保绑定的事件只执行一次,执行后自动解绑,不会积累多余的事件:

$(document).on("click", ".delete_item", function(e) {
    e.preventDefault();
    var user_id = $(this).attr('data-user_id');
    var text_modal = "Are you sure?";
    $('.modal-body').text(text_modal);
    $('#modal-delete').modal('show');

    // 用.one()代替.on(),事件仅执行一次
    $('.confirmation').one('click', function() {
        $.ajax({
            type: 'GET',
            url: 'delete.php',
            data: { 'user_id': user_id },
            success: function(html) {
                // 移除对应行后,页面已经更新,不需要刷新
                $('.ui-sortable li[data-itemid="' + user_id + '"]').remove();
                // location.reload(); // 建议删除这行,提升用户体验
            }
        });
    });

    // 模态框关闭时(不管点取消还是点击空白处),清空残留事件
    $('#modal-delete').one('hidden.bs.modal', function () {
        $('.confirmation').off('click');
    });
});

方案2:把确认事件移到外部,用全局变量存当前ID(更清晰)

这种方法只给确认按钮绑定一次事件,用变量存储当前要删除的ID,从根源避免重复绑定:

// 全局变量存储当前要删除的user_id
var currentDeleteId = null;

// 仅绑定一次确认按钮的事件
$('.confirmation').on('click', function() {
    if (!currentDeleteId) return; // 没有ID则不执行
    $.ajax({
        type: 'GET',
        url: 'delete.php',
        data: { 'user_id': currentDeleteId },
        success: function(html) {
            $('.ui-sortable li[data-itemid="' + currentDeleteId + '"]').remove();
            // location.reload();
            currentDeleteId = null; // 清空变量
        }
    });
});

// 删除按钮点击事件
$(document).on("click", ".delete_item", function(e) {
    e.preventDefault();
    currentDeleteId = $(this).attr('data-user_id');
    var text_modal = "Are you sure?";
    $('.modal-body').text(text_modal);
    $('#modal-delete').modal('show');
});

// 取消或弹窗关闭时清空变量
$('.cancellation').on('click', function() {
    currentDeleteId = null;
});

$('#modal-delete').on('hidden.bs.modal', function () {
    currentDeleteId = null;
});

额外建议

去掉location.reload()!因为你已经通过.remove()把对应的行从DOM中删掉了,页面已经实时更新,刷新页面反而会打断用户操作体验,除非后端返回的内容需要同步其他数据,否则完全没必要。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 00:02:49