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

发布于 2024-07-27 00:32:04 字数 931 浏览 5 评论 0 原文

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

任何人都可以发布示例吗?

Here in stackoverflow, if you started to make changes then you attempt to navigate away from the page, a javascript confirm button shows up and asks: "Are you sure you want to navigate away from this page?" blee blah bloo...

Has anyone implemented this before, how do I track that changes were committed?
I believe I could do this myself, I am trying to learn the good practices from you the experts.

I tried the following but still doesn't work:

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

Can anyone post an example?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

强者自强 2024-08-03 00:32:04

更新(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?";
});

Update (2017)

Modern browsers now consider displaying a custom message to be a security hazard and it has therefore been removed from all of them. Browsers now only display generic messages. Since we no longer have to worry about setting the message, it is as simple as:

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

Read below for legacy browser support.

Update (2013)

The orginal answer is suitable for IE6-8 and FX1-3.5 (which is what we were targeting back in 2009 when it was written), but is rather out of date now and won't work in most current browsers - I've left it below for reference.

The window.onbeforeunload is not treated consistently by all browsers. It should be a function reference and not a string (as the original answer stated) but that will work in older browsers because the check for most of them appears to be whether anything is assigned to onbeforeunload (including a function that returns null).

You set window.onbeforeunload to a function reference, but in older browsers you have to set the returnValue of the event instead of just returning a string:

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

You can't have that confirmOnPageExit do the check and return null if you want the user to continue without the message. You still need to remove the event to reliably turn it on and off:

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

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

Original answer (worked in 2009)

To turn it on:

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

To turn it off:

window.onbeforeunload = null;

Bear in mind that this isn't a normal event - you can't bind to it in the standard way.

To check for values? That depends on your validation framework.

In jQuery this could be something like (very basic example):

$('input').change(function() {
    if( $(this).val() != "" )
        window.onbeforeunload = "Are you sure you want to leave?";
});
习惯那些不曾习惯的习惯 2024-08-03 00:32:04

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>

这样,只有在用户导航离开时,才会警告他已更改文本区域,并且在实际提交表单时不会出现提示。

The onbeforeunload Microsoft-ism is the closest thing we have to a standard solution, but be aware that browser support is uneven; e.g. for Opera it only works in version 12 and later (still in beta as of this writing).

Also, for maximum compatibility, you need to do more than simply return a string, as explained on the Mozilla Developer Network.

Example: Define the following two functions for enabling/disabling the navigation prompt (cf. the MDN example):

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

Then define a form like this:

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

This way, the user will only be warned about navigating away if he has changed the text area, and will not be prompted when he's actually submitting the form.

世界如花海般美丽 2024-08-03 00:32:04

要在 Chrome 和 Safari 中实现此功能,您必须按照以下

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

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

To make this work in Chrome and Safari, you would have to do it like this

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

Reference: https://developer.mozilla.org/en/DOM/window.onbeforeunload

疯了 2024-08-03 00:32:04

使用 JQuery 这个东西很容易做。 因为您可以绑定到集合。

仅仅执行 onbeforeunload 是不够的,您只想在有人开始编辑内容时触发导航。

With JQuery this stuff is pretty easy to do. Since you can bind to sets.

Its NOT enough to do the onbeforeunload, you want to only trigger the navigate away if someone started editing stuff.

述情 2024-08-03 00:32:04

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

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

jquerys 'beforeunload' worked great for me

$(window).bind('beforeunload', function(){
    if( $('input').val() !== '' ){
        return "It looks like you have input you haven't submitted."
    }
});
执手闯天涯 2024-08-03 00:32:04

这是一种在表单中输入任何数据时显示消息的简单方法,而在提交表单时则不显示消息:

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

This is an easy way to present the message if any data is input into the form, and not to show the message if the form is submitted:

$(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;
    });
})
゛时过境迁 2024-08-03 00:32:04

要扩展Keith已经令人惊叹的答案

自定义警告消息

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

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 将 this 绑定到表单元素

如果使用 jQuery,可以轻松地将 this 绑定到表单的所有元素,如下所示:

$("#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");
    // ...
}

To expand on Keith's already amazing answer:

Custom warning messages

To allow custom warning messages, you can wrap it in a function like this:

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

Then just call that function with your custom message:

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

Enabling navigation again

To re-enable navigation, all you need to do is set window.onbeforeunload to null. Here it is, wrapped in a neat little function that can be called anywhere:

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

Using jQuery to bind this to form elements

If using jQuery, this can easily be bound to all of the elements of a form like this:

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

Then to allow the form to be submitted:

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

Dynamically-modified forms:

preventNavigation() and enableNavigation() can be bound to any other functions as needed, such as dynamically modifying a form, or clicking on a button that sends an AJAX request. I did this by adding a hidden input element to the form:

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

Then any time I want to prevent the user from navigating away, I trigger the change on that input to make sure that preventNavigation() gets executed:

function somethingThatModifiesAFormDynamically() {

    // Do something that modifies a form

    // ...
    $("#dummy_input").trigger("change");
    // ...
}
戏剧牡丹亭 2024-08-03 00:32:04

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

截至69.0.3497.92,Chrome尚未达到标准。 不过,已提交错误报告,并且审核正在进行中。 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';

The standard states that prompting can be controlled by canceling the beforeunload event or setting the return value to a non-null value. It also states that authors should use Event.preventDefault() instead of returnValue, and the message shown to the user is not customizable.

As of 69.0.3497.92, Chrome has not met the standard. However, there is a bug report filed, and a review is in progress. Chrome requires returnValue to be set by reference to the event object, not the value returned by the handler.

It is the author's responsibility to track whether changes have been made; it can be done with a variable or by ensuring the event is only handled when necessary.

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

执笏见 2024-08-03 00:32:04

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

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

When the user starts making changes to the form, a boolean flag will be set. If the user then tries to navigate away from the page, you check that flag in the window.onunload event. If the flag is set, you show the message by returning it as a string. Returning the message as a string will popup a confirmation dialog containing your message.

If you are using ajax to commit the changes, you can set the flag to false after the changes have been committed (i.e. in the ajax success event).

梦旅人picnic 2024-08-03 00:32:04

在这里尝试一下它可以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>

Here try this it works 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>
反目相谮 2024-08-03 00:32:04

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

You can add an onchange event on the textarea (or any other fields) that set a variable in JS. When the user attempts to close the page (window.onunload) you check the value of that variable and show the alert accordingly.

仅冇旳回忆 2024-08-03 00:32:04

根据该线程上的所有答案,我编写了以下代码并且它对我有用。

如果您只有一些需要检查 onunload 事件的 input/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?";   
    };
});

Based on all the answers on this thread, I wrote the following code and it worked for me.

If you have only some input/textarea tags which requires an onunload event to be checked, you can assign HTML5 data-attributes as data-onunload="true"

for eg.

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

and the Javascript (jQuery) can look like this :

$(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?";   
    };
});
似最初 2024-08-03 00:32:04

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

here is my 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>

And so this is how I did something similar in 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!");
}
}
糖粟与秋泊 2024-08-03 00:32:04

来自 WebAPIs->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 = '';
})

From the WebAPIs->WindowEventHandler->onbeforeunload, it recommends use window.addEventListener() and the beforeunload event, instead of onbeforeunload.

Syntax example

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

Note: The HTML specification states that authors should use the Event.preventDefault() method instead of using Event.returnValue to prompt the user.

So, in terms of your case, the code should look like this:

//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 = '';
})
瘫痪情歌 2024-08-03 00:32:04

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

It can be easily done by setting a ChangeFlag to true, on onChange event of TextArea. Use javascript to show confirm dialog box based on the ChangeFlag value. Discard the form and navigate to requested page if confirm returns true, else do-nothing.

半窗疏影 2024-08-03 00:32:04

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

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

What you want to use is the onunload event in JavaScript.

Here is an example: http://www.w3schools.com/jsref/event_onunload.asp

咆哮 2024-08-03 00:32:04

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

There is an "onunload" parameter for the body tag you can call javascript functions from there. If it returns false it prevents navigating away.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文