如何在离开当前页面之前触发与JS的对话

时间:2009-02-05 06:17:19

标签: javascript

如果用户更改了表单中的内容,然后点击任何会将他引导到另一个页面的链接,我想触发一个弹出窗口,其中包含“你想在离开之前保存吗?”选项。

我该怎么做?

2 个答案:

答案 0 :(得分:12)

示例:

 <script type="text/javascript">
     var shouldConfirm = false;
     window.onbeforeunload = function() {
         if(shouldConfirm) {
             return "You have made unsaved changes. Would you still like to leave this page?";
         }
     }
 </script>

 <input id="FullName" type="text" />
 <script type="text/javascript">
     document.getElementById('FullName').onchange = function() {
         shouldConfirm = true;
     }
 </script>

4GuysFromRolla.com上有一篇完整的文章。

答案 1 :(得分:0)

这是如何做到的,但这并不总是可靠的:

<html>
<head>
<script type="text/javascript">
function leaving()
 {
    if(confirm("Would you like to save?"))
     {
        //Save info
     }
    else
     {
        //Don't save
     }
 }
</script>
</head>
<body onUnload="leaving()">
<!--Stuff-->
</body>
</html>