【发布时间】: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 Chromev52
标签: javascript forms validation onbeforeunload