Javascript - 离开页面时的确认

Javascript - Confirmation when leaving page(Javascript - 离开页面时的确认)

本文介绍了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 - 离开页面时的确认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Javascript - 离开页面时的确认

基础教程推荐