【问题标题】:onbeforeunload in JavaScript doesn't workJavaScript 中的 onbeforeunload 不起作用
【发布时间】:2016-08-25 06:30:57
【问题描述】:

我似乎在使用 onbeforeunload 事件警告用户离开带有未保存表单数据的页面时遇到问题。我写了一个最小的页面,但仍然无法正常工作。如果我正在导航或重新加载页面,此页面有时会警告我,但有时不会,而且我看不出是什么原因。有时它会询问我何时未更改表单值。我已经查看了其他问题,据我所知,我所做的是正确的。我做错了什么?

<html>
<body>

<script>

window.onload = function() { doRecord(); };
window.onbeforeunload = function() { return doCheck(); };

setTimeout( doCheck, 5000 );;

var storeValue = "";

function doRecord()
{
  var inp = document.getElementById( "theinput" );
  storeValue = inp.value;
  console.log( "Running doRecording" );
}

function doCheck()
{
  console.log( "Running doCheck" );

  var inp = document.getElementById( "theinput" );

  console.log( "Comparing '" + storeValue + "' to '" + inp.value + "'" );

  if ( storeValue != inp.value )
  {
    console.log( "It has changed" );
    return "Are you sure that you want to leave this page, value has changed";
  }
  else
  {
    console.log( "It's OK" );
    return null;
  }
}

</script>

<h3>Form</h3>
<form id="myform" method="post" action="process.php" onsubmit="window.onbeforeunload = null" >
<input type="text" size="20" name="sometext" id="theinput" value="Change This" />
<p>
<input type=submit />
</form>

</body>
</html>

【问题讨论】:

  • 只有当您的输入为空时才会出现警告??
  • window.onload 等待图像和其他资源(如外部 CSS 和 JS)完全加载。您可能在 onload 触发之前开始编辑,因此您的更新值存储在 storeValue 中。 console.logs 是怎么说的?
  • 您的代码运行良好
  • 当输入中有内容时会出现警告。我可以从 console.log 消息中看到该函数正在正确检测该字段是否已更改。没有要加载的图像或外部 CSS 或其他内容。我可以从控制台消息中看到正确的值存储在变量中。 @Abanoub - 您使用的是什么浏览器(和操作系统)?我在 Mac OS 上的 safari 中对此进行了测试。编辑:我刚刚在 Mac OS 上尝试过 firefox,它似乎工作正常。
  • 我在ubuntu 14上使用Google Chrome v52

标签: javascript forms validation onbeforeunload


【解决方案1】:

此代码看起来不正确: &lt;form id="myform" method="post" action="process.php" onsubmit="window.onbeforeunload = null" &gt;

这不应该是: &lt;form id="myform" method="post" action="process.php" onsubmit="return (window.onbeforeunload()== null)" &gt;

我在创建 here 的小提琴中进行了此更改,现在看起来没问题。

【讨论】:

  • 这将停止提交表单。 OP 的代码正在删除卸载处理程序,以便表单可以加载下一页。你是正确的,虽然 onsubmit 应该返回一些真实的东西。
  • 我认为 OP 打算这样做,即如果 window.onbeforeunload 中的检查失败,则停止表单提交,尽管它看起来很奇怪,我还没有看到它以这种方式使用
  • 我相信目标是为了避免丢失他们的更改,用户必须提交表单而不是离开或关闭选项卡。
  • 这是正确的。我想在表单提交的情况下禁用 onbeforeunload 检查。但是,问题的发生与提交的表单无关。我检查了代码:
    但这并没有影响问题。
  • 我试过 Dhananjay 的小提琴,但它对我不起作用。我可以更改字段中的文本,在地址栏中输入新地址,然后导航离开,并且不会收到任何警告。有时我会收到一条消息,有时却没有。
猜你喜欢
  • 2021-03-13
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
  • 1970-01-01
  • 2012-10-18
  • 1970-01-01
  • 1970-01-01
  • 2019-02-26
相关资源
最近更新 更多