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

问题描述 投票:242回答:17

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

任何人都可以发一个例子吗

javascript html message onbeforeunload confirm
17个回答
336
投票

更新(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;

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

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

在jQuery中,这可能是(非常基本的例子):

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

2
投票

当用户开始更改表单时,将设置布尔标志。如果用户然后尝试离开页面,则在window.onunload事件中检查该标志。如果设置了该标志,则通过将其作为字符串返回来显示该消息。将消息作为字符串返回将弹出包含您的消息的确认对话框。

如果使用ajax提交更改,则可以在提交更改后将标志设置为false(即在ajax成功事件中)。


2
投票

提示的standard states可以通过取消beforeunload事件或将返回值设置为non-null value来控制。它还声明作者应使用Event.preventDefault()而不是returnValue,并向用户is not customizable显示消息。

截至69.0.3497.92,Chrome尚未达到标准。然而,有一个bug report提交,并且review正在进行中。 Chrome需要通过引用事件对象来设置returnValue,而不是处理程序返回的值。

作者有责任追踪是否已做出更改;它可以使用变量完成,也可以确保仅在必要时处理事件。

window.addEventListener('beforeunload', function (e) {
    // Cancel the event as stated by the standard.
    e.preventDefault();
    // Chrome requires returnValue to be set.
    e.returnValue = '';
});
    
window.location = 'about:blank';

1
投票

您可以在textarea(或任何其他字段)中添加onchange事件,该事件在JS中设置变量。当用户尝试关闭页面(window.onunload)时,您检查该变量的值并相应地显示警报。


1
投票

根据这个帖子的所有答案,我写了下面的代码,它对我有用。

如果您只有一些需要检查onunload事件的输入/ textarea标记,则可以将HTML5数据属性指定为data-onunload="true"

例如。

<input type="text" data-onunload="true" />
<textarea data-onunload="true"></textarea>

而Javascript(jQuery)可能如下所示:

$(document).ready(function(){
    window.onbeforeunload = function(e) {
        var returnFlag = false;
        $('textarea, input').each(function(){
            if($(this).attr('data-onunload') == 'true' && $(this).val() != '')
                returnFlag = true;
        });

        if(returnFlag)
            return "Sure you want to leave?";   
    };
});

1
投票

这是我的HTML

<!DOCTYPE HMTL>
<meta charset="UTF-8">
<html>
<head>
<title>Home</title>
<script type="text/javascript" src="script.js"></script>
</head>

 <body onload="myFunction()">
    <h1 id="belong">
        Welcome To My Home
    </h1>
    <p>
        <a id="replaceME" onclick="myFunction2(event)" href="https://www.ccis.edu">I am a student at Columbia College of Missouri.</a>
    </p>
</body>

所以这就是我在javaScript中做类似的事情

var myGlobalNameHolder ="";

function myFunction(){
var myString = prompt("Enter a name", "Name Goes Here");
    myGlobalNameHolder = myString;
    if (myString != null) {
        document.getElementById("replaceME").innerHTML =
        "Hello " + myString + ". Welcome to my site";

        document.getElementById("belong").innerHTML =
        "A place you belong";
    }   
}

// create a function to pass our event too
function myFunction2(event) {   
// variable to make our event short and sweet
var x=window.onbeforeunload;
// logic to make the confirm and alert boxes
if (confirm("Are you sure you want to leave my page?") == true) {
    x = alert("Thank you " + myGlobalNameHolder + " for visiting!");
}
}

0
投票

可以通过在TextArea的onChange事件上将ChangeFlag设置为true来轻松完成。使用javascript根据ChangeFlag值显示确认对话框。如果确认返回true,则丢弃表单并导航到请求的页面,否则执行任何操作。


0
投票

您要使用的是JavaScript中的onunload事件。

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


-1
投票

你可以从那里调用javascript函数的body标签有一个“onunload”参数。如果它返回false,则会阻止导航。


37
投票

onbeforeunload Microsoft-ism是我们对标准解决方案最接近的事情,但要注意浏览器支持不均匀;例如对于Opera,它仅适用于12及更高版本(截至本文撰写时仍为测试版)。

此外,为了获得最大的兼容性,您需要做的不仅仅是返回一个字符串,如Mozilla Developer Network所述。

示例:定义以下两个用于启用/禁用导航提示的功能(参见MDN示例):

function enableBeforeUnload() {
    window.onbeforeunload = function (e) {
        return "Discard changes?";
    };
}
function disableBeforeUnload() {
    window.onbeforeunload = null;
}

然后定义一个这样的表单:

<form method="POST" action="" onsubmit="disableBeforeUnload();">
    <textarea name="text"
              onchange="enableBeforeUnload();"
              onkeyup="enableBeforeUnload();">
    </textarea>
    <button type="submit">Save</button>
</form>

这样,只有在用户更改了文本区域时才会向用户发出警告,并且在他实际提交表单时不会提示用户。


19
投票

要在Chrome和Safari中使用,您必须这样做

window.onbeforeunload = function(e) {
    return "Sure you want to leave?";
};

参考:https://developer.mozilla.org/en/DOM/window.onbeforeunload


18
投票

With JQuery这个东西很容易做到。因为你可以绑定到集合。

它不足以进行onbeforeunload,你只想触发导航,如果有人开始编辑东西。


13
投票

jquery'afterunload'对我很有用

$(window).bind('beforeunload', function(){
    if( $('input').val() !== '' ){
        return "It looks like you have input you haven't submitted."
    }
});

11
投票

如果有任何数据输入到表单中,这是一种简单的方法来呈现消息,而不是在提交表单时显示消息:

$(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;
    });
})

11
投票

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


7
投票

要扩展Keith's already amazing answer

自定义警告消息

要允许自定义警告消息,您可以将其包装在如下函数中:

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

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

        // For Chrome, Safari, IE8+ and Opera 12+
        return message;
    };
    window.onbeforeunload = confirmOnPageExit;
}

然后用你的自定义消息调用该函数:

preventNavigation("Baby, please don't go!!!");

再次启用导航

要重新启用导航,您需要做的就是将window.onbeforeunload设置为null。在这里,它包裹在一个可以在任何地方调用的简洁小功能:

function enableNavigation() {
    window.onbeforeunload = null;
}

使用jQuery将其绑定到表单元素

如果使用jQuery,这很容易绑定到表单的所有元素,如下所示:

$("#yourForm :input").change(function() {
    preventNavigation("You have not saved the form. Any \
        changes will be lost if you leave this page.");
});

然后允许提交表单:

$("#yourForm").on("submit", function(event) {
    enableNavigation();
});

动态修改形式:

preventNavigation()enableNavigation()可以根据需要绑定到任何其他函数,例如动态修改表单,或单击发送AJAX请求的按钮。我这样做是通过向表单添加一个隐藏的输入元素:

<input id="dummy_input" type="hidden" />

然后,只要我想阻止用户导航,我就会触发对该输入的更改,以确保执行preventNavigation()

function somethingThatModifiesAFormDynamically() {

    // Do something that modifies a form

    // ...
    $("#dummy_input").trigger("change");
    // ...
}

3
投票

在这里尝试这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>
© www.soinside.com 2019 - 2024. All rights reserved.