在这里的stackoverflow,如果你开始做改变,然后你试图导航离开页面,一个javascript确认按钮显示,并询问:“你确定你想导航离开这个页面吗?”

以前有人实现过这个吗?我如何跟踪已提交的更改? 我相信我自己可以做到这一点,我正在努力从你们这些专家那里学习好的做法。

我尝试了以下方法,但仍然不起作用:

<html>
<body>
    <p>Close the page to trigger the onunload event.</p>
    <script type="text/javascript">
        var changes = false;        
        window.onbeforeunload = function() {
            if (changes)
            {
                var message = "Are you sure you want to navigate away from this page?\n\nYou have started writing or editing a post.\n\nPress OK to continue or Cancel to stay on the current page.";
                if (confirm(message)) return true;
                else return false;
            }
        }
    </script>

    <input type='text' onchange='changes=true;'> </input>
</body>
</html>

有人能举个例子吗?


当前回答

试试这个,100%有效

<html>
<body>
<script>
var warning = true;
window.onbeforeunload = function() {  
  if (warning) {  
    return "You have made changes on this page that you have not yet confirmed. If you navigate away from this page you will lose your unsaved changes";  
    }  
}

$('form').submit(function() {
   window.onbeforeunload = null;
});
</script>
</body>
</html>

其他回答

你想要使用的是JavaScript中的onunload事件。

这里有一个例子:http://www.w3schools.com/jsref/event_onunload.asp

对于正在寻找简单解决方案的新人,只需尝试Areyousure.js

如果表单中输入了任何数据,这是一种简单的显示消息的方法,如果表单已提交,则不显示消息:

$(function () {
    $("input, textarea, select").on("input change", function() {
        window.onbeforeunload = window.onbeforeunload || function (e) {
            return "You have unsaved changes.  Do you want to leave this page and lose your changes?";
        };
    });
    $("form").on("submit", function() {
        window.onbeforeunload = null;
    });
})

body标签有一个"onunload"参数,你可以从那里调用javascript函数。如果返回false,则阻止导航离开。

这可以很容易地通过设置一个ChangeFlag为true,在TextArea的onChange事件。使用javascript根据ChangeFlag值显示确认对话框。如果确认返回true,则丢弃表单并导航到请求页面,否则什么都不做。