SweetAlert2弹窗isConfirm回调不生效,表单提交场景下如何解决?
问题原因
- 语法不匹配:你当前使用的回调函数写法是SweetAlert1的旧版本语法,SweetAlert2早已废弃该写法,改为通过Promise的
then()方法接收用户操作结果,所以旧的isConfirm回调不会被触发。 - 事件冲突:你在复选框上绑定了内联
onchange="this.form.submit()"事件,该事件执行优先级高于你通过jQuery绑定的click事件,会直接触发表单提交打断SweetAlert的交互逻辑。
解决方法
- 首先移除复选框上的内联
onchange事件,避免事件冲突。 - 将SweetAlert调用改为符合SweetAlert2规范的Promise写法,确认后手动提交表单即可。
修改后的表单代码
<form id="myForm" data-flag="0" action="" method="POST"> @csrf <input type="checkbox" id="btn-submit" name="wallet_checked"> </form>
修改后的交互脚本
$(document).on('change', '#btn-submit', function(e) { e.preventDefault(); const form = $(this).closest('form'); Swal.fire({ title: "Attention!", text: "Are you sure you want to make this", icon: "warning", allowEscapeKey: false, allowOutsideClick: false, showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes", cancelButtonText: "No", showLoaderOnConfirm: true, closeOnConfirm: false }).then((result) => { if (result.isConfirmed) { console.log("YES"); // 确认后提交表单 form.submit(); } else if (result.dismiss === Swal.DismissReason.cancel) { // 点取消时还原复选框状态 $(this).prop('checked', !$(this).prop('checked')); } }); });
内容的提问来源于stack exchange,提问作者user16723850
相关产品推荐
相关产品推荐

