2016-08-25 40 views
0

我似乎有问题使用onbeforeunload事件来警告用户,如果他们从未保存的表单数据导航离开页面。我写了一个最小的页面,但仍然不起作用。如果我正在导航或重新加载页面,此页面有时会提醒我,但有时不会,并且我看不到原因。有时它会问我什么时候没有改变表单的值。我看过其他问题,据我所知,我所做的是对的。我究竟做错了什么?JavaScript中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

window.onload会等待图像和其他资源(如外部CSS和JS)完全加载。你可能在onload被触发之前开始编辑,所以你的更新值被存储在storeValue中。 console.log说什么? – jedifans

+0

您的代码正常工作 – Abanoub

回答

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这个现在看来OK小提琴这种变化。

+0

这将停止提交表单。 OP的代码是删除卸载处理程序,以便表单可以加载下一页。你是正确的,onsubmit应该返回一些truthy虽然。 – jedifans

+0

我以为OP打算这样即停止表单提交如果在window.onbeforeunload'检查失败,虽然它看起来很奇怪,我没有看到它用这种方式 – Dhananjay

+0

我相信我们的目标是,为了避免失去他们的变化,用户必须提交表单而不是导航或关闭标签。 – jedifans