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
相关产品推荐
相关产品推荐

