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

有人能举个例子吗?


body标签有一个"onunload"参数,你可以从那里调用javascript函数。如果返回false,则阻止导航离开。

当用户开始对表单进行更改时,将设置一个布尔标志。如果用户尝试离开页面,则检查窗口中的标志。onunload事件。如果设置了标志,则通过以字符串形式返回消息来显示消息。以字符串形式返回消息将弹出一个包含您的消息的确认对话框。

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

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

更新(2017)

现代浏览器现在认为显示自定义消息是一种安全隐患,因此它已从所有浏览器中删除。浏览器现在只显示通用消息。因为我们不再需要担心设置消息,它就像这样简单:

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

阅读下面的内容,了解传统浏览器的支持。

更新(2013)

最初的答案适用于IE6-8和FX1-3.5(这是我们在2009年写它时的目标),但现在已经过时了,不能在大多数当前的浏览器中工作-我把它留在下面作为参考。

窗外。并非所有浏览器都一致对待Onbeforeunload。它应该是一个函数引用,而不是一个字符串(如最初的答案所述),但在旧的浏览器中也可以工作,因为对大多数浏览器的检查似乎是是否有任何东西被分配给onbeforeunload(包括返回null的函数)。

你设置窗口。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?";
});

你想要使用的是JavaScript中的onunload事件。

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

使用JQuery,这是非常容易做到的。因为你可以绑定到集合。

这是不够的做onbeforeunload,你想只触发导航离开,如果有人开始编辑东西。

这可以很容易地通过设置一个ChangeFlag为true,在TextArea的onChange事件。使用javascript根据ChangeFlag值显示确认对话框。如果确认返回true,则丢弃表单并导航到请求页面,否则什么都不做。

onbeforeunload Microsoft-ism是我们拥有的最接近标准解决方案的东西,但请注意浏览器的支持是不均衡的;例如,对于Opera,它只适用于版本12及更高的版本(在撰写本文时仍处于测试阶段)。

此外,为了最大限度地兼容,您需要做的不仅仅是返回一个字符串,正如Mozilla开发者网络中所解释的那样。

示例:定义以下两个函数用于启用/禁用导航提示符(参见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>

这样,只有当用户更改了文本区域时,才会提示用户导航离开,而当用户实际提交表单时不会收到提示。

要在Chrome和Safari中运行,你必须这样做

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

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

jquery 'beforeunload'对我来说非常有用

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

根据这个线程上的所有答案,我写了下面的代码,它对我来说是有效的。

如果你只有一些输入/文本区域标签,需要检查onunload事件,你可以将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?";   
    };
});

如果表单中输入了任何数据,这是一种简单的显示消息的方法,如果表单已提交,则不显示消息:

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

试试这个,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>

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

让我来进一步解释一下基斯已经很惊人的答案:

自定义警告消息

为了允许自定义警告消息,你可以像这样把它包装在一个函数中:

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!!!");

再次启用导航

要重新启用导航,您所需要做的就是设置窗口。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();
});

Dynamically-modified形式:

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

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

然后,每当我想阻止用户导航离开时,我就会触发输入上的更改,以确保preventNavigation()被执行:

function somethingThatModifiesAFormDynamically() {

    // Do something that modifies a form

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

这是我的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!");
}
}

该标准指出,可以通过取消beforeunload事件或将返回值设置为非空值来控制提示。它还声明作者应该使用Event.preventDefault()而不是returnValue,并且显示给用户的消息是不可定制的。

截至69.0.3497.92 Chrome未达到标准。然而,有一个错误报告存档,审查正在进行中。Chrome要求returnValue通过引用事件对象来设置,而不是由处理程序返回的值。

作者有责任跟踪是否进行了修改;这可以通过变量来实现,也可以通过确保只在必要时处理事件来实现。

窗口。addEventListener('beforeunload',函数(e) { //取消标准规定的事件。 e.preventDefault (); // Chrome需要设置returnValue e.returnValue = "; }); 窗口。Location = '大约:空白';

从webapi ->WindowEventHandler->onbeforeunload,它建议使用window.addEventListener()和beforeunload事件,而不是onbeforeunload。

语法的例子

window.addEventListener("beforeunload", function(event) { ... });
window.onbeforeunload = function(event) { ... };

注意:HTML规范规定作者应该使用Event. preventdefault()方法而不是使用Event。returnValue来提示用户。

所以,就你的情况而言,代码应该是这样的:

//javascript
window..addEventListener("beforeunload", function(event) { 
    //your code

    // If you prevent default behaviour in Mozilla Firefox prompt will always be shown
    e.preventDefault();

    // Chrome requires returnValue to be set
    e.returnValue = '';
})