我需要在用户离开页面之前警告他们关于未保存的更改(这是一个非常常见的问题)。

window.onbeforeunload = handler

这是可行的,但它会引发一个默认对话框,其中包含一个烦人的标准消息,其中包装了我自己的文本。我需要完全替换标准消息,这样我的文本是清晰的,或者(甚至更好)用jQuery的模态对话框替换整个对话框。

到目前为止,我失败了,我还没有找到其他似乎有答案的人。这可能吗?

Javascript在我的页面:

<script type="text/javascript">   
    window.onbeforeunload = closeIt;
</script>

closeIt()函数:

function closeIt()
{
  if (changes == "true" || files == "true")
  {
      return "Here you can append a custom message to the default dialog.";
  }
}

使用jQuery和jqModal我已经尝试了这种事情(使用自定义确认对话框):

$(window).beforeunload(function () {
    confirm('new message: ' + this.href + ' !', this.href);
    return false;
});

这也不工作-我似乎不能绑定到beforeunload事件。


当前回答

使用专用版本的“绑定”命令“一”。事件处理程序第一次执行后,将自动将其作为事件处理程序删除。

$(window).one("beforeunload", BeforeUnload);

其他回答

对我来说,使用jQuery并在IE8、Chrome和Firefox中进行测试的方法是:

$(window).bind("beforeunload",function(event) {
    if(hasChanged) return "You have unsaved changes";
});

重要的是,如果不需要提示,不要返回任何东西,因为IE和其他浏览器的行为在这里是不同的。

虽然在某些情况下对该方框无能为力,但您可以拦截点击链接的人。对我来说,这对于大多数情况来说都是值得的,作为备用方案,我留下了unload事件。

我使用的是Boxy而不是标准的jQuery Dialog,它可以在这里获得:http://onehackoranother.com/projects/jquery/boxy/

$(':input').change(function() {
    if(!is_dirty){
        // When the user changes a field on this page, set our is_dirty flag.
        is_dirty = true;
    }
});

$('a').mousedown(function(e) {
    if(is_dirty) {
        // if the user navigates away from this page via an anchor link, 
        //    popup a new boxy confirmation.
        answer = Boxy.confirm("You have made some changes which you might want to save.");
    }
});

window.onbeforeunload = function() {
if((is_dirty)&&(!answer)){
            // call this if the box wasn't shown.
    return 'You have made some changes which you might want to save.';
    }
};

您可以附加到另一个事件,并根据单击的锚的类型筛选更多内容,但这对我和我想做的事情都有效,并可作为其他人使用或改进的示例。我想把这个分享给那些想要这个解决方案的人。

我已经剪掉了代码,所以这可能无法正常工作。

这不能在chrome现在做,以避免垃圾邮件,参考javascript onbeforeunload不显示自定义消息了解更多细节。

我也遇到过同样的问题,我可以用自己的对话框来显示我的信息,但我面临的问题是: 1)它在所有导航上都给出了消息,我想它只用于近距离点击。 2)与我自己的确认消息,如果用户选择取消它仍然显示浏览器的默认对话框。

以下是我找到的解决方案代码,我写在我的主页上。

function closeMe(evt) {
    if (typeof evt == 'undefined') {
        evt = window.event; }
    if (evt && evt.clientX >= (window.event.screenX - 150) &&
        evt.clientY >= -150 && evt.clientY <= 0) {
        return "Do you want to log out of your current session?";
    }
}
window.onbeforeunload = closeMe;
 <script type="text/javascript">
        window.onbeforeunload = function(evt) {
            var message = 'Are you sure you want to leave?';
            if (typeof evt == 'undefined') {
                evt = window.event;
            }       
            if (evt) {
                evt.returnValue = message;
            }
            return message;
        } 
    </script>

参考http://www.codeprojectdownload.com