SweetAlert 2中变量重新赋值不生效问题求助
问题原因与解决方案
问题根源
Swal.fire是异步操作,它的.then()回调函数只会在用户点击确认/取消按钮后才会执行。而你代码里的console.log(check)和if(check)判断是在弹窗还没处理完用户交互时就同步执行了,这时候check还是初始值false,自然不会触发跳转逻辑。
修复方案
方案1:将跳转逻辑移到.then()回调内
直接把页面跳转的代码放到用户确认后的回调里,确保只有用户确认后才执行跳转:
function deletePost(event) { event.preventDefault(); // 先阻止默认跳转行为 Swal.fire({ title: "Are you sure to reject this candidate?", icon: "warning", showCancelButton: true, confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", confirmButtonText: "Yes, i'am sure", customClass: { title: "my-title", content: "my-content", confirmButton: "my-confirm-button", cancelButton: "my-cancel-button", }, }).then((result) => { if (result.isConfirmed) { // 等成功提示框关闭后再跳转 Swal.fire( "Rejected Successfully!", "The Candidate will be informed.", "success" ).then(() => { window.location.href = event.currentTarget.getAttribute("href"); }); } }); }
方案2:使用async/await简化异步逻辑
用async/await让异步代码看起来像同步执行,逻辑更清晰:
async function deletePost(event) { event.preventDefault(); // 等待用户完成弹窗操作 const result = await Swal.fire({ title: "Are you sure to reject this candidate?", icon: "warning", showCancelButton: true, confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", confirmButtonText: "Yes, i'am sure", customClass: { title: "my-title", content: "my-content", confirmButton: "my-confirm-button", cancelButton: "my-cancel-button", }, }); if (result.isConfirmed) { // 等待成功提示框关闭 await Swal.fire( "Rejected Successfully!", "The Candidate will be informed.", "success" ); // 执行跳转 window.location.href = event.currentTarget.getAttribute("href"); } }
内容的提问来源于stack exchange,提问作者Thắng Quang
相关产品推荐
相关产品推荐

