繁体   English   中英

JS:如何找出导致window.onbeforeunload()的原因:F5或提交?

[英]JS: How to find out who caused the window.onbeforeunload(): F5 or submit?

我在一个小型Web应用程序上工作,用户刷新浏览器后,需要显示确认对话框。 我使用window.onbeforeunload = function() { ...} 问题在于它不仅在刷新时被调用,而且在提交后也被调用。 我有一个问题:我可以找出window.onbeforeunload是由刷新还是由Submit元素引起的吗?

您可以为各种事件编写事件处理程序,这些事件处理程序会使您离开页面并具有标识符来管理状态。 然后,您可以在onbeforepageunload函数中使用此标识符来执行您想执行的任何操作。 这是一个代码示例,该示例查找输入类型Submit并设置标识符。 同样,您可以为锚标记添加一个,依此类推。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>

</head>
<body>
<form action="">
  <input type="submit" value="Submit">
</form>
</body>
  <script>
    var submit_was_clicked = false;

    window.addEventListener("beforeunload", function (event) {
      if(submit_was_clicked){
        console.log('submit button clicked')
      }else{
        console.log('on before unload');
      }
    });

    document.addEventListener("click", function(e) {
      if (e.target.type.toLowerCase() === 'submit') {
          submit_was_clicked = true;
      }
    }, true);
  </script>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM