You need to enable JavaScript to run this app. Bootstrap V5 & jQuery 模态框二次打开后绑定的关闭事件不触发问题
优惠活动
大模型
产品
解决方案
定价
更多

Bootstrap V5 & jQuery 模态框二次打开后绑定的关闭事件不触发问题

问题根因

你的代码在用户确认关闭模态框的逻辑中,调用了$(this).off("hide.bs.modal"),这行代码会直接移除所有绑定在模态框上的hide.bs.modal监听事件,所以模态框首次关闭后,再次打开时已经没有对应的关闭事件监听,自然不会触发SweetAlert2的确认提示。
另外你手动移除.modal-backdrop、清除body类名和样式的操作属于多余操作,Bootstrap原生的模态框隐藏逻辑会自动处理这些内容,额外手动处理反而可能引发样式异常。

修复方法

你只需要给原生的modal("hide")方法传递自定义标记,在hide.bs.modal的回调中判断该标记,存在标记时直接放行不拦截即可,不需要移除事件监听。

修改后的完整代码如下:

(function ($) {
    "use strict";
    $(window).on("load", function () {
        if ($(".modal").length) {
            $(".modal").modal("show");
            $(".modal").on("shown.bs.modal", function (e) {
                e.preventDefault();
                $(".spinner")
                    .removeClass("d-none")
                    .delay(3000)
                    .fadeOut(500, function () {
                        $(this).addClass("d-none");
                    });
            });
            $(".modal").on("hide.bs.modal", function (e) {
                // 判断如果是手动确认触发的关闭,直接放行不拦截
                if(e.namespace && e.namespace === 'manual-confirm') return;
                e.preventDefault();
                var swalWithBootstrapButtons = Swal.mixin({
                    customClass: {
                        confirmButton: "btn btn-primary",
                        cancelButton: "btn btn-danger me-3",
                    },
                    buttonsStyling: false,
                });
                swalWithBootstrapButtons
                    .fire({
                        title: "Are you sure?",
                        text: "You won't be able to revert this!",
                        icon: "warning",
                        confirmButtonText: "<i class='fas fa-check-circle me-1'></i> Yes, I am!",
                        cancelButtonText: "<i class='fas fa-times-circle me-1'></i> No, I'm Not",
                        showCancelButton: true,
                        reverseButtons: true,
                        focusConfirm: false,
                    })
                    .then((result) => {
                        if (result.isConfirmed) {
                            // 传递自定义命名空间标记,触发关闭时跳过拦截
                            $(this).modal("hide").trigger($.Event("hide.bs.modal", { namespace: "manual-confirm" }));
                        }
                    });
            });
        }
    });
})(window.jQuery);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 23:36:03