提示用户在离开页面时进行保存 [英] Prompting user to save when they leave a page

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

问题描述

我需要提醒用户在他们离开页面时保存他们的工作。我已经尝试onbeforeunload,但我需要显示一个样式的提示不是通常的对话框。 Facebook已经成功实现了这一点(如果你有一个Facebook帐户,编辑你的个人资料信息,并转到另一个页面而不保存,你会得到一个样式化的提示)。我也试过jQuery的卸载,但似乎没有办法阻止卸载事件传播。

解决方案

仔细查看Facebook正在做什么:如果您点击页面上的链接 ,但是在地址栏中输入新网址,点击书签或在浏览器历史记录中浏览返回内容时没有任何问题。



如果这对您有用,很简单:只需在页面上的每个链接中添加一个 click 事件处理程序,并从中触发您的程式化确认。由于这些处理程序会在页面本身触发的任何导航事件之前被调用,所以您可以在处理程序中执行任何您想要的操作 - 保存数据,完全取消事件,记录然后,如果您确实需要或想要响应外部触发的导航事件,您必须使用 onbeforeunload 。对,对话是蹩脚的,你不能取消事件 - 这是我们支付所有在90年代滥用这些功能的丑陋白痴的代价。对不起......


I need to prompt a user to save their work when they leave a page. I've tried onbeforeunload but I need to show a styled prompt not the usual dialog box. Facebook has managed to achieve this (if you have a Facebook account, edit your profile info and go to another page without saving and you get a styled prompt). I've also tried jquery unload but there doesn't seem to be a way to stop the unload event from propagating.

解决方案

Take a closer look at what Facebook is doing: you get a prompt if you click a link on the page, but nothing when entering a new URL in the address bar, clicking a bookmark, or navigating Back in your browser's history.

If that works for you, it's easy enough to do: simply add a click event handler to every link on the page, and trigger your stylized confirmation from it. Since these handlers will get called prior to the start of any navigation events triggered from within the page itself, you can pretty much do whatever you want in the handler - save data, cancel the event entirely, record the intended destination and postpone it 'till after they confirm...

However, if you do need or want to respond to navigation events triggered externally, you'll have to use onbeforeunload. And yes, the dialog is crappy, and you can't cancel the event - that's the price we pay for all the scandalous idiots abusing such features back in the '90s. Sorry...

这篇关于提示用户在离开页面时进行保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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