【问题标题】:Is there a way to do something similar to onbeforeunload for an AJAX form?有没有办法为 AJAX 表单做类似于 onbeforeunload 的事情?
【发布时间】:2017-04-21 04:41:39
【问题描述】:

遗憾的是,我们不得不使用自制的类似 spa 的引擎,它会劫持所有导航并通过 ajax 进行操作。

我正在寻找一种能够将标签添加到form 的方法,可能是这样的:

<form data-confirm-unsaved=""></form>

这会导致绑定到此form 的卸载,无论是实际的整个页面卸载(例如有人关闭选项卡或键入 URL)还是单击任何被劫持的导航元素...但我不希望在提交/保存form 时触发它。

我有什么不工作的代码的开始大纲:

$('[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 事件绑定到form...只能绑定window,我能否获得一些关于如何执行此操作的线索?

预期的结果是,当form 通过提交以外的任何方式卸载时,如果他们真的想这样做,就会出现确认信息。

【问题讨论】:

  • 预期结果是什么?
  • 我的第一个想法是在你的所谓 home-brew, spa-like engine 中进行必要的更改 - home-brew 建议你有“源”代码 - 即没有缩小或丑化或混淆
  • 查看预期结果的编辑,我可以修改自制引擎。
  • 问题上下文中“卸载”的定义是什么?
  • unloaded = 从 DOM 中移除,或者说 DOM 被移除了

标签: javascript jquery ajax typescript onbeforeunload


【解决方案1】:

您可以在MutationEvent 处使用附加到&lt;body&gt;MutationObserver,并将childList 选项设置为true,检查&lt;form&gt; 是否已删除节点。

<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    相关资源
    最近更新 更多