【问题标题】:Is there a way to set window.onbeforeunload to null before an object is click?有没有办法在点击对象之前将 window.onbeforeunload 设置为 null?
【发布时间】:2021-04-18 20:16:07
【问题描述】:

我正在使用 wtforms,这是我的提交按钮:

{{ form.submit(class="btn btn-outline-info") }}

这是我的 onbeforeunload 函数:

<script type="text/javascript">
  window.onbeforeunload = function() {
  return "Are you sure you want to navigate away?";
  }
</script>

我知道在普通的 html 表单中我可能可以使用 jquery 来执行此操作:

参考:

jquery-function-before-form-submission stackoverflow discussion

clear onbeforunload stackoverflow discussion

<head>
  <script src="jquery-3.5.1.min.js"></script>
</head>
<script>
$('#myform').submit(function(event) {

 event.preventDefault(); //this will prevent the default submit

  window.onbeforeunload = null;
  
 $(this).unbind('submit').submit(); // continue the submit unbind preventDefault
})
<script>

当我使用这些 wtforms 对象时我应该怎么做? (ps我不熟悉js或jquery....请指出我做错了什么......)

提前致谢!

【问题讨论】:

  • 我怀疑你需要打电话给preventDefault()。如果您打算以任何方式提交。我只是将 onbeforeunload 设置为 null 并返回 true(返回 true 让提交继续)。

标签: javascript html jquery


【解决方案1】:

一个选项是使用addEventListener 而不是onbeforeunload

const myFunc = function() {
  return "Are you sure you want to navigate away?";
}
window.addEventListener('beforeunload', myFunc);

然后在submit方法上,移除监听器

window.removeEventListener('beforeunload', myFunc);

【讨论】:

    【解决方案2】:

    所以这可能不是最好的方法!但这是一个非常好的解决方法!由于 wtforms 对象不允许将任何附加功能(即 onclick 或任何信息)传递到 {} 花括号中,因此解决方法是将其包装起来!所以添加所有这些的主要事情是调用一个函数来禁用onbeforeunload,因此一个快速的解决方案将是

    onbeforeunload 函数(保持不变):

    <script type="text/javascript">
      window.onbeforeunload = function() {
      return "Are you sure you want to navigate away?";
      }
    </script>
    

    禁用onbeforeunload功能:

    <script>
      function submit()
      {
        window.onbeforeunload = null;
      }
    </script>
    

    对于提交按钮:

    <a onclick="submit()">{{ form.submit(class="btn btn-outline-info") }}</a>
    

    无法想象我花了这么长时间才弄明白,顺便说一句,感谢@terrymorse,他让我知道这个问题实际上是多么简单!感谢所有 cmets 并提供解决方案并编辑我的问题的人!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2023-03-24
      • 2010-11-23
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      相关资源
      最近更新 更多