javascript - 提交更改时如何显示 "Are you sure you want to navigate away from this page?"?

标签 javascript html message onbeforeunload confirm

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

谁能发个例子?

最佳答案

更新(2017 年)

现代浏览器现在认为显示自定义消息存在安全隐患,因此 removed从他们所有人。浏览器现在只显示通用消息。既然我们再也不用担心设置消息了,就这么简单:

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

请记住,这不是正常事件 - 您不能以标准方式绑定(bind)到它。

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

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

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

关于javascript - 提交更改时如何显示 "Are you sure you want to navigate away from this page?"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1119289/

相关文章:

javascript - 带有自定义日期的数据dimple.js

javascript - 为什么我的 Canvas 除了 Angular 落外都是空白的?

javascript - 使用 jquery 在 html 中动态插入行?

php - 刷新http请求头中的数据

html - CSS3 选框效果 - 难倒

jms - 销毁JMS消息监听器

javascript - Mac 和 Windows 之间设置 NODE_ENV 不同

javascript - 更改 DrawingManager 默认光标

grails - Grails中的默认错误消息不在 View 中呈现

c# - Java <-> C# 套接字 : cant receive messages