小编典典

如何显示“您确定要离开此页面吗?” 何时提交更改?

html

在stackoverflow中,如果您开始进行更改,然后尝试离开该页面,则会显示一个javascript确认按钮并询问:“确定要离开该页面吗?” blee
blah bloo …

之前有人实施过此功能,如何跟踪所做的更改?我相信自己可以做到,我正在尝试向您的专家学习良好做法。

我尝试了以下操作,但仍然无法正常工作:

<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>

有人可以举一个例子吗?


阅读 684

收藏
2020-05-10

共1个答案

小编典典

更新(2017)

现在,现代浏览器认为显示自定义消息是一种安全隐患,因此已将从所有浏览器中删除。现在,浏览器仅显示常规消息。由于我们不再需要担心设置消息的问题,因此它很简单:

// Enable navigation prompt
window.onbeforeunload = function() {
    return true;
};
// Remove navigation prompt
window.onbeforeunload = null;

阅读以下内容以获取旧版浏览器支持。

更新(2013)

原始答案适用于IE6-8和FX1-3.5(这是我们在2009年编写时所针对的目标),但是现在已经过时了,在大多数当前的浏览器中都无法使用-
我已经离开了下面以供参考。

window.onbeforeunload所有浏览器都没有一致的处理。它应该是函数引用,而不是字符串(如原始答案所述),但是它将在较旧的浏览器中工作,因为对大多数浏览器的检查似乎是是否已分配了任何内容onbeforeunload(包括返回的函数null)。

您设置window.onbeforeunload为函数引用,但是在较旧的浏览器中,您必须设置returnValue事件的,而不仅仅是返回字符串:

var confirmOnPageExit = function (e) 
{
    // If we haven't been passed the event get the window.event
    e = e || window.event;

    var message = 'Any text will block the navigation and display a prompt';

    // For IE6-8 and Firefox prior to version 4
    if (e) 
    {
        e.returnValue = message;
    }

    // For Chrome, Safari, IE8+ and Opera 12+
    return message;
};

confirmOnPageExit如果您希望用户继续操作而不收到消息,则无法进行检查并返回null。您仍然需要删除事件以可靠地打开和关闭该事件:

// Turn it on - assign the function that returns the string
window.onbeforeunload = confirmOnPageExit;

// Turn it off - remove the function entirely
window.onbeforeunload = null;

原始答案(2009年工作)

打开它:

window.onbeforeunload = "Are you sure you want to leave?";

要将其关闭:

window.onbeforeunload = null;

请记住,这不是正常事件-您无法以标准方式绑定到该事件。

要检查值?这取决于您的验证框架。

在jQuery中,可能类似于(非常基本的示例):

$('input').change(function() {
    if( $(this).val() != "" )
        window.onbeforeunload = "Are you sure you want to leave?";
});
2020-05-10