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

jQuery使用SweetAlert2调用preventDefault后如何在确认后正常触发点击事件

解决方案

核心原因

你二次触发点击时会再次执行绑定的delete_all_product事件处理函数,重新走「阻止默认行为+弹出确认框」的逻辑,因此形成死循环。同时你当前代码还存在this指向错误:then回调内的this并不指向触发点击的输入框元素,直接调用$(this)会无法拿到预期对象。


推荐方案(标志位法,可复用确认逻辑)

该方案无需解绑事件,每次点击都会触发确认流程,适配绝大多数需要操作二次确认的场景:

function delete_all_product( _e ) {
    const $this = $(this);
    // 已完成确认的场景直接放行,不执行弹框逻辑
    if ($this.data('is_confirmed')) {
        // 重置标志位,保证下次点击仍需确认
        $this.data('is_confirmed', false);
        return;
    }
    _e.preventDefault();
    Swal.fire({
        title: '你确定要将区域切换为'+$this.val()+'吗?',
        icon: 'info',
        confirmButtonText: '确定',
        showCancelButton: true,
    }).then((result) => {
        if (result.isConfirmed){
            po.populate_product_slider(); 
            $('.product-list-item').remove();
            // 标记为已确认,下次触发点击时直接走默认逻辑
            $this.data('is_confirmed', true);
            $this.trigger('click');                             
        }
    }); 
}

$('input[name="prod_reg"]').click(po.delete_all_product);

可选方案(解绑事件法,仅需单次确认)

如果你只需要第一次点击触发确认,后续点击无需二次验证可以用该方案:

function delete_all_product( _e ) {
    const $this = $(this);
    _e.preventDefault();
    Swal.fire({
        title: '你确定要将区域切换为'+$this.val()+'吗?',
        icon: 'info',
        confirmButtonText: '确定',
        showCancelButton: true,
    }).then((result) => {
        if (result.isConfirmed){
            po.populate_product_slider(); 
            $('.product-list-item').remove();
            // 先解绑当前点击事件,避免二次触发弹框
            $this.off('click', po.delete_all_product);
            $this.trigger('click');                             
        }
    }); 
}

$('input[name="prod_reg"]').click(po.delete_all_product);

内容的提问来源于stack exchange,提问作者Never Stop Learning

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 07:39:02