如何知道用户是否点击了Javascript onbeforeunload对话框上的取消? [英] Way to know if user clicked Cancel on a Javascript onbeforeunload Dialog?

查看:482
本文介绍了如何知道用户是否点击了Javascript onbeforeunload对话框上的取消?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当有人试图离开特定页面而没有保存他们的工作时,我弹出一个对话框。我使用Javascript的onbeforeunload事件,效果很好。

I am popping up a dialog box when someone tries to navigate away from a particular page without having saved their work. I use Javascript's onbeforeunload event, works great.

现在我想在用户点击出现的对话框上的取消时运行一些Javascript代码(说他们不会我想离开页面。)

Now I want to run some Javascript code when the user clicks "Cancel" on the dialog that comes up (saying they don't want to navigate away from the page).

这可能吗?我也在使用jQuery,所以可能有一个像我之前可以绑定的beforeunloadcancel这样的事件吗?

Is this possible? I'm using jQuery as well, so is there maybe an event like beforeunloadcancel I can bind to?

UPDATE :我们的想法是实际保存并将用户引导到不同的网页,如果他们选择取消

UPDATE: The idea is to actually save and direct users to a different webpage if they chose cancel

推荐答案

你可以这样做:

$(function() {
    $(window).bind('beforeunload', function() {
        setTimeout(function() {
            setTimeout(function() {
                $(document.body).css('background-color', 'red');
            }, 1000);
        },1);
        return 'are you sure';
    });
}); 

第一个 setTimeout 方法中的代码已包含延迟1ms。这只是将函数添加到 UI队列中。由于 setTimeout 异步运行,Javascript解释器将继续直接调用 return 语句,从而触发浏览器模态对话框。这将阻止 UI队列,并且在模式关闭之前,不会执行第一个 setTimeout 中的代码。如果用户按下取消,它将触发另一个在大约一秒钟内触发的setTimeout。如果用户确认为ok,则用户将重定向,并且第二个setTimeout永远不会被触发。

The code within the first setTimeout method has a delay of 1ms. This is just to add the function into the UI queue. Since setTimeout runs asynchronously the Javascript interpreter will continue by directly calling the return statement, which in turn triggers the browsers modal dialog. This will block the UI queue and the code from the first setTimeout is not executed, until the modal is closed. If the user pressed cancel, it will trigger another setTimeout which fires in about one second. If the user confirmed with ok, the user will redirect and the second setTimeout is never fired.

示例: http://www.jsfiddle.net/NdyGJ/2/

这篇关于如何知道用户是否点击了Javascript onbeforeunload对话框上的取消?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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