
本文讲解如何在 SweetAlert 弹窗确认提交成功后,不依赖 location.reload(),直接通过 JavaScript 隐藏或移除目标 元素,并修正原代码中 localStorage 调用错误与异步执行逻辑问题。
本文讲解如何在 sweetalert 确认提交成功后,**不依赖 `location.reload()`**,直接通过 javascript 隐藏或移除目标 `
` 元素,并修正原代码中 localstorage 调用错误与异步执行逻辑问题。
在使用 SweetAlert 处理表单提交时,开发者常误以为“页面重载”是更新 ui 的唯一方式。但实际中,location.reload() 不仅造成用户体验中断(白屏、滚动重置、状态丢失),还掩盖了更优雅、可控的 dom 操作方案。针对问题中需隐藏
的需求,完全无需刷新页面——只需在 ajax 成功回调中调用 jquery 的 .hide() 或 .remove() 即可。
✅ 正确做法:隐藏元素 + 修复逻辑错误
首先,原代码存在两处关键问题:
- localStorage.getItem(‘rightcontent’, data) 语法错误:getItem() 只接受一个参数(key),第二个参数会被忽略;
- localStorage.removeItem(‘leftcontent’) 和 localStorage.getItem(…) 写在 .then() 回调内,但被 location.reload() 阻断执行(页面刷新后 js 上下文立即销毁,后续语句永不执行)。
以下是优化后的完整代码,已移除 location.reload(),改用 DOM 操作实现即时隐藏,并修复 localStorage 逻辑:
$(document).ready(function() { $(document).on('click', '#approve', function() { Swal.fire({ title: 'Are you sure?', icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes', cancelButtonText: 'Cancel' }).then((result) => { if (result.isConfirmed) { // 推荐使用 isConfirmed 替代 value(v11+ 更语义化) $('.leftforms').each(function() { const $form = $(this); const valuesToSend = $form.serialize(); const actionUrl = $form.attr('action') || 'data.php'; const method = $form.attr('method') || 'POST'; $.ajax({ url: actionUrl, type: method, data: valuesToSend, dataType: 'json' // 显式声明期望 JSON 响应,便于 error 处理 }) .done(function(response) { Swal.fire({ title: 'Data berhasil diupdate!', text: response.message || 'Update completed.', icon: 'success', timer: 1500, showConfirmButton: false }).then(() => { // ✅ 安全执行 DOM 操作与 localStorage $('#content1').hide(); // 或 .remove() 彻底移除 localStorage.removeItem('leftcontent'); // 若需读取 rightcontent,正确写法如下: // const rightData = localStorage.getItem('rightcontent'); }); }) .fail(function(xhr, status, error) { Swal.fire('Error', 'Failed to submit: ' + error, 'error'); }); }); } }); }); });
⚠️ 注意事项与最佳实践
-
.hide() vs .remove():
- $(‘#content1’).hide() 仅设置 display: none,元素仍存在于 DOM 中,可随时 .show() 恢复;
- $(‘#content1’).remove() 从 DOM 中彻底删除节点,不可逆(除非重新渲染);根据业务需求选择。
-
避免 location.reload() 的典型场景:
当操作仅影响局部 UI(如隐藏提示框、更新列表项、切换按钮状态),应优先采用 DOM 操作 + 数据驱动更新,提升性能与体验。 -
localStorage 使用规范:
-
增强健壮性建议:
- 添加 dataType: ‘json’ 并检查 response.message 是否存在,防止因后端未返回预期字段导致脚本报错;
- 使用 Swal.fire().then(() => { … }) 的链式回调确保操作顺序;
- 对多个表单(.leftForms)并行提交时,注意并发控制(如需串行,可改用 async/await + for…of)。
通过以上重构,你不仅解决了“隐藏 div”的原始需求,更构建了更可靠、可维护、符合现代 Web 开发规范的交互流程。