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

ole*_*ius 9 javascript

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

我怎样才能做到这一点?

End*_*ssa 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>
Run Code Online (Sandbox Code Playgroud)

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