在这里的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>

有人能举个例子吗?

我需要在用户离开页面之前警告他们关于未保存的更改(这是一个非常常见的问题)。

window.onbeforeunload = handler

这是可行的,但它会引发一个默认对话框,其中包含一个烦人的标准消息,其中包装了我自己的文本。我需要完全替换标准消息,这样我的文本是清晰的,或者(甚至更好)用jQuery的模态对话框替换整个对话框。

到目前为止,我失败了,我还没有找到其他似乎有答案的人。这可能吗?

Javascript在我的页面:

<script type="text/javascript">   
    window.onbeforeunload = closeIt;
</script>

closeIt()函数:

function closeIt()
{
  if (changes == "true" || files == "true")
  {
      return "Here you can append a custom message to the default dialog.";
  }
}

使用jQuery和jqModal我已经尝试了这种事情(使用自定义确认对话框):

$(window).beforeunload(function () {
    confirm('new message: ' + this.href + ' !', this.href);
    return false;
});

这也不工作-我似乎不能绑定到beforeunload事件。