关闭选项卡时要求确认 [英] Ask for confirm when closing a tab

查看:116
本文介绍了关闭选项卡时要求确认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我关闭一些浏览器我要一个消息框出现,并问我,如果我真的要关闭该页面或没有,有两个按钮,如果我点击我的页面则该选项卡不会被关闭。

When I close my page on some browser I want a message box to appear and to ask me if I really want to close the page or not, with two buttons and if I click No then this tab won't be closed.

我怎么能这样做?

推荐答案

您要听上的的 - 标准的 beforeunload 事件。这是几乎所有的浏览器都支持,希望这是众所周知的粘附在W3C标准极其严格的歌剧。

You need to listen on the non-standard beforeunload event. This is supported by almost all browsers, expect of Opera which is known to adhere the W3C standards extremely strictly.

下面是一个开球例如:

window.onbeforeunload = function() {
    return "Hey, you're leaving the site. Bye!";
};

这个消息将在怎样的一个确认对话框中显示出来。此消息将显示正确的的客户端卸载的页面。这可以是一个浏览器关闭,的的也可以像点击一个链接或页面提交表单一个简单的导航作用!

This message will show up in kind of a confirmation dialogue. This message will show up right before the client unloads the page. That can be a browser close, but that can also be a simple navigational action like clicking a link or submitting a form in the page!

您将最有可能也想将其关闭(只是设置为)就内部链接被点击或内部表单提交。你即不想惹恼与直观的行为最终用户。你可以通过监听的单击所需的链接和所需要的形式提交事件事件。 jQuery的可能会有很大的帮助在这里,因为它在crossbrowsercompatible方式,这样你就不需要写> 20行JS code的为此:

You would most probably also like to turn it off (just set to null) whenever an internal link is clicked or an internal form is submitted. You namely don't want to annoy endusers with unintuitive behaviour. You can do that by listening on the click event of the desired links and the submit event of the desired forms. jQuery may be of great help here since it does that in crossbrowsercompatible way so that you don't need to write >20 lines of JS code for this:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    window.onbeforeunload = function() {
        return "You're leaving the site.";
    };
    $(document).ready(function() {
        $('a[rel!=ext]').click(function() { window.onbeforeunload = null; });
        $('form').submit(function() { window.onbeforeunload = null; });
    });
</script>

您只需要给所有的外部链接的事实标准属性的rel =转来表示,这些都是外部链接。

You only need to give all external links the defacto standard attribute rel="ext" to denote that those are external links.

<a href="http://google.com" rel="ext">Google</a>

这篇关于关闭选项卡时要求确认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆