关闭标签时要求确认 [英] Ask for confirm when closing a tab

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

问题描述

当我在某些浏览器上关闭我的页面时,我希望出现一个消息框并询问我是否真的要关闭页面,有两个按钮,如果我单击 No 然后这个标签不会关闭.

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 事件.

You need to listen on the beforeunload event.

这是一个启动示例:

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!

您很可能也希望在点击内部链接或提交内部表单时将其关闭(只需设置为 null).您不想以不直观的行为惹恼最终用户.您可以通过监听所需链接的 click 事件和所需表单的 submit 事件来做到这一点.jQuery 在这里可能会有很大帮助,因为它以跨浏览器兼容的方式做到这一点,因此您无需编写 > 20 行用于此的 JS 代码:

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="ext" 来表示这些是外部链接.

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天全站免登陆