javascript - 外部表单提交后重新加载页面

标签 javascript

我遇到了一个外部应用程序将 html 表单注入(inject)到我的代码中的情况。要对表单执行任何操作,我首先需要等待单击事件,因为只有按下触发按钮后才会注入(inject)表单,然后我添加了一个延迟以确保加载表单,然后需要重新加载提交表单后,该页面。 请参阅下面的代码

_birthdayRefresh() {
    const birthdayActionButton = document.querySelector(".lion-rule-item--birthday .lion-action-button");
    birthdayActionButton.addEventListener("click", () => {
      setTimeout(() => {
        const birthdayForm = document.querySelector("form.lion-birthday-entry-form");
        if (birthdayForm) {
          birthdayForm.addEventListener("submit", () => {
            location.reload();
          });
        }
      }, 1000);
    });
  }

这种工作...但是,我认为有时会在提交表单之前重新加载页面,并且不会保存表单中的数据。如何确保仅在表单成功提交后才重新加载页面?

最佳答案

尝试使用MutationObserver。这是一种更可靠的方法来检测表单何时添加到 DOM。它是现代浏览器的内置功能,允许您观察 DOM 的更改并在这些更改发生时执行代码。显然,setTimeout 并不能保证某些外部表单已完全加载。

_birthdayRefresh() {
   const birthdayActionButton = document.querySelector(".lion-rule-item-- 
        birthday .lion-action-button");

 birthdayActionButton.addEventListener("click", () => {
    // Create a MutationObserver to observe changes in the DOM
    const observer = new MutationObserver(mutations => {
    mutations.forEach(mutation => {
      mutation.addedNodes.forEach(node => {
        if (node.matches && node.matches('form.lion-birthday-entry-form')) {
          // Once the form is added, attach the submit event listener
          node.addEventListener('submit', () => {
            location.reload();
          });

          // Stop observing once the form is found
          observer.disconnect();
        }
    });
  });
});

    // Start observing the DOM for added nodes
    observer.observe(document.body, { childList: true, subtree: true });
  });
}

代码未经测试,请谨慎使用。另外请将 type="button" 添加到您的触发按钮。如果您不指定它可能会意外提交表单

关于javascript - 外部表单提交后重新加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77800620/

相关文章:

javascript - JS - 如何获取节点开头和当前插入符号(文本光标)位置之间的文本?

javascript - 如何使下拉菜单出现在幻灯片上?

javascript - 如何 'unrender' MathJax方程?

javascript - 应用没有 ng-class 的类?

javascript - AngularJS:$http 和 $q promise 的工作方式不同

javascript - 在 Safari 中设置跨域 cookie

javascript - 如何测试Nodejs请求回调监听器?

javascript - 解析对象以匹配接口(interface)

javascript - 试图将 javascript 压缩为 for 循环

javascript - 简单的Three.js动画