遗憾的是,我们现在的处境是必须使用自制的、类似水疗中心的引擎,该引擎会劫持所有导航并通过 ajax
来完成。
我正在寻找一种能够将标签添加到表单
的方法,也许像这样:
<form data-confirm-unsaved=""></form>
这应该会导致绑定(bind)到此表单
的卸载,无论是实际的整个页面卸载(例如有人关闭选项卡或输入 URL)还是单击任何被劫持的内容导航元素...但我不希望在提交/保存表单
时触发它。
我有一个不工作代码的开始大纲:
$('[data-confirm-unsaved]').on('beforeunload', function (e) {
let isUnload = true;
let message = $(this).attr('[data-confirm-unsaved]');
if (message == '')
message = "This data is unsaved. Are you certain that you want to cancel?";
if (isFormDirty($(this)))
isUnload = confirm(message);
if (isUnload)
e.preventDefault();
});
当然,我不能将 beforeunload
事件绑定(bind)到 form
...只有 window
,我可以得到一些线索吗我该如何去做呢?
预期的结果是,当表单
通过除提交之外的任何方式卸载时,如果他们确实想这样做,则输入内容不正确,会出现确认。
最佳答案
您可以使用MutationObserver
附于<body>
与 childList
选项设置为true
,位于MutationEvent
,检查是否 <form>
已删除节点。
<body>
<form id="form">
<input>
</form>
<script>
const form = document.getElementById("form");
const observer = new MutationObserver(([{removedNodes}]) => {
if (removedNodes.length) {
// do stuff if `form` is removed from `document.body`
checkRemovedNodes: for (const node of removedNodes) {
if (node === form) {
console.log(`${node.tagName}#${node.id} removed from document`);
break checkRemovedNodes;
}
}
}
});
// remove `form` from `document` in `3000` milliseconds
observer.observe(document.body, {
childList: true
});
setTimeout(() => document.body.removeChild(form), 3000);
</script>
</body>
关于javascript - 有没有办法对 AJAX 表单执行类似于 onbeforeunload 的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43534091/