Javascript-离开页面时进行确认 [英] Javascript - Confirmation when leaving page

查看:87
本文介绍了Javascript-离开页面时进行确认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个基本的弹出窗口,该窗口询问用户是否真的要离开页面,这与如果我在编写此消息的过程中尝试关闭窗口的过程类似,将在该网站上发生.

I'm trying to implement a basic popup window that asks the user if they really want to leave a page, similar to what would happen on this site if I tried to close the window half way through writing this message.

我意识到这通常是不被接受的,但是我有充分的理由要这样做.

I realise this is something that is generally frowned upon but I have good reason for wanting to do it.

我通过使用以下代码使其工作:

I have got it working by using the following code:

function confirm_exit(e) {
        if(!e) e = window.event;

        e.cancelBubble = true;
        e.returnValue = 'Are you sure you want to leave?'; 

        if (e.stopPropagation) {
            e.stopPropagation();
            e.preventDefault();
        }
    }

但是,我真正想做的是在他们离开页面时显示消息,除非他们通过单击两个链接之一离开.

However, what I would really like to do is display the message whenever they leave the page, UNLESS they leave by clicking one of two links.

(我刚刚意识到这听起来像是我可能想强迫他们点击广告或其他东西!)

(I've just realised that sounds like I might want to force them to click an advert or something!)

使用此功能的原因是在预订过程结束时,用户可以在确认之前确认预订或添加其他预订. (这是我不希望显示弹出消息的两种可能性,弹出消息中只会显示您的预订尚未确认,确定要离开吗?"之类的信息.)

The reason for using this is at the end of a booking process, where users can either confirm their booking or add further bookings before making the confirmation. (These would be the two possibilities that I would NOT like the popup message to display, the message in the pop up would just say something like 'Your booking is not yet confirmed, are you sure you wish to leave?).

反正有实现这一目标的方法吗?

Is there anyway to achieve this?

任何建议表示赞赏.

谢谢.

推荐答案

从头开始:

<head>
...
<script type="text/javascript">
var disabledConfirm_exit=false;
</script>
</head>

在允许离开的两个链接中,您可以添加

In the two links allowed to leave, you can add

onclick="disabledConfirm_exit=true;"

在confirm_exit内部

And inside the confirm_exit

function confirm_exit(e) {
    if(disabledConfirm_exit) return;
    if(!e) e = window.event;

    e.cancelBubble = true;
    e.returnValue = 'Are you sure you want to leave?'; 

    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
}

这篇关于Javascript-离开页面时进行确认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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