您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

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

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

原始答案适用于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;

打开它:

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?";
});
javascript 2022/1/1 18:21:35 有289人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶