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

有人能举个例子吗?


当前回答

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

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

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

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

其他回答

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

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

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

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

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

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

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

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