The beforeunload
event fires whenever the user leaves your page for any reason.(每当用户出于任何原因离开您的页面时,就会触发beforeunload
事件。)
For example, it will be fired if the user submits a form, clicks a link, closes the window (or tab), or goes to a new page using the address bar, search box, or a bookmark.(例如,如果用户提交表单,单击链接,关闭窗口(或选项卡)或使用地址栏,搜索框或书签进入新页面,则将触发该事件。)
You could exclude form submissions and hyperlinks (except from other frames) with the following code:(您可以使用以下代码排除表单提交和超链接(其他框架除外):)
var inFormOrLink;
$('a').on('click', function() { inFormOrLink = true; });
$('form').on('submit', function() { inFormOrLink = true; });
$(window).on("beforeunload", function() {
return inFormOrLink ? "Do you really want to close?" : null;
})
For jQuery versions older than 1.7, try this:(对于1.7之前的jQuery版本,请尝试以下操作:)
var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });
$(window).bind("beforeunload", function() {
return inFormOrLink ? "Do you really want to close?" : null;
})
The live
method doesn't work with the submit
event, so if you add a new form, you'll need to bind the handler to it as well.(live
方法不适用于submit
事件,因此,如果添加新表单,则还需要将处理程序绑定到该表单。)
Note that if a different event handler cancels the submit or navigation, you will lose the confirmation prompt if the window is actually closed later.(请注意,如果其他事件处理程序取消了提交或导航,则如果稍后实际上关闭了该窗口,则将丢失确认提示。)
You could fix that by recording the time in the submit
and click
events, and checking if the beforeunload
happens more than a couple of seconds later.(你可以通过记录的时间解决这个问题submit
和click
事件,并检查是否beforeunload
发生超过几秒钟后。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…