我似乎在使用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>
答案 0 :(得分:0)
此代码看起来不正确:
<form id="myform" method="post" action="process.php" onsubmit="window.onbeforeunload = null" >
这不应该是:
<form id="myform" method="post" action="process.php" onsubmit="return (window.onbeforeunload()== null)" >
我在我创建的小提琴中做了这个改变here现在这似乎没问题。