Sweet Alert 2弹窗无限重复弹出无法关闭问题求助
问题描述
我通过如下函数创建了一个按钮:
function onDataBound(e) { $(this).find(".btn-group").append(` <a class='dropdown-item text-danger is-active' onclick='showSweetAlert(${dataItem.AdvertiserId}, ${dataItem.IsActive})' type='button'>Mark Inactive </a>`); });
该按钮会调用如下showSweetAlert函数:
function showSweetAlert(id, isActive){ document.addEventListener('click',function(e) { if (isActive) { Swal.fire ({ title:"Are you sure?", text:"This will inactivate the advertiser!", icon:"warning", showCancelButton:!0, confirmButtonColor:"#2ab57d", cancelButtonColor:"#fd625e", confirmButtonText:"Inactivate" }).then(function(result){ if(result.isConfirmed){ $.ajax({ url:'/Advertisers/ActiveAdvertiser?id='+id+'&isActive='+isActive, method: 'POST', success: function(r){ Swal.fire("Inactivated!", "Advertiser inactivated successfully", "success"); }, error: function (request) { console.log(request.responseText) Swal.fire("Error!", "Something went wrong, please try again`", "warning"); } }); } else{ Swal.fire("Error!", "Something went wrong, please try again", "warning"); } } ) } }) }
点击按钮触发弹窗后,点击弹窗的任意按钮,弹窗状态不变,还会无限重复弹出,无法关闭,求排查问题。
问题排查与修复
核心问题:重复绑定全局点击事件
每次调用showSweetAlert时,都会给document新增一个全局点击事件监听器。第一次点击按钮触发函数后,绑定了一个监听器;当点击弹窗按钮时,这个全局点击事件会被再次触发,重新执行Swal.fire,直接导致弹窗无限弹出。
修复方案
直接移除document.addEventListener('click', ...)的包裹,让函数直接执行弹窗逻辑即可:
function showSweetAlert(id, isActive){ if (isActive) { Swal.fire({ title:"Are you sure?", text:"This will inactivate the advertiser!", icon:"warning", showCancelButton: true, confirmButtonColor:"#2ab57d", cancelButtonColor:"#fd625e", confirmButtonText:"Inactivate" }).then(function(result){ if(result.isConfirmed){ $.ajax({ url:'/Advertisers/ActiveAdvertiser?id='+id+'&isActive='+isActive, method: 'POST', success: function(r){ Swal.fire("Inactivated!", "Advertiser inactivated successfully", "success"); }, error: function (request) { console.log(request.responseText) Swal.fire("Error!", "Something went wrong, please try again", "warning"); } }); } else if(result.dismiss === Swal.DismissReason.cancel) { // 点击取消按钮时给出友好提示,不要误报错误 Swal.fire("Cancelled", "Advertiser remains active", "info"); } }); } }
额外优化点
- 将
showCancelButton:!0改为可读性更强的showCancelButton:true - 区分弹窗取消的场景,避免把用户主动取消的操作当成错误提示
- 修正了原错误提示中的多余反引号
内容的提问来源于stack exchange,提问作者Demian
相关产品推荐
相关产品推荐

