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

有人能举个例子吗?


当前回答

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

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

其他回答

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

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

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>

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

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

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

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

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