简体   繁体   English

确认是否在卸载/退出对话框上,是否按下了后退按钮?

[英]Confirm dialog box on unload/exit UNLESS the back button is pressed?

I have some simple code to display a confirm dialog box when the user tries to leave my form: 当用户尝试离开我的表单时,我有一些简单的代码来显示确认对话框:

window.onbeforeunload = askConfirm;
function askConfirm(){
    return "Your answers will be lost.";
}

But this is a multi-page form and they frequently press back to change some values on a previous page. 但这是一个多页的表单,他们经常按返回以更改上一页的某些值。

But when they do this dialog box still comes up. 但是当他们这样做时,仍然会出现该对话框。

Is there a way around this? 有没有解决的办法?

The answer I would suggest unfortunately doesn't actually answer your question but is a solution of a kind. 不幸的是,我建议的答案实际上并没有回答您的问题,而是一种解决方案。 The only possible solution here, imv, is to make sure that a user clicking the back button doesn't actually create an issue by storing the form answers from all pages. 唯一可行的解​​决方案imv是通过存储所有页面的表单答案来确保用户单击“后退”按钮实际上不会造成问题。 In the case of PHP I would store them in a session ( $_SESSION ). 对于PHP,我会将它们存储在一个会话中( $_SESSION )。 You have to recognise that users use the back button more than any other UI element within a browser. 您必须认识到,用户使用后退按钮的次数比浏览器中任何其他UI元素都要多。 If your form truly has to be across a number of pages then you need to make sure the data they have entered is persistent across all these pages. 如果您的表单确实必须跨多个页面,那么您需要确保他们输入的数据在所有这些页面上都是持久的。 I would actually provide a navigation for this within your own interface. 我实际上将在您自己的界面中为此提供导航。 Provide a clear sequential process visually and allow instant navigation through this process where possible. 在视觉上提供清晰的顺序过程,并在可能的情况下允许立即导航通过该过程。

I don't see a way to specifically detect whether the user pressed "back" or any other browser button. 我没有找到一种方法来专门检测用户是否按了“后退”或任何其他浏览器按钮。 This is outside the site's scope. 这不在站点范围内。

Only one solution comes to mind: Show the confirmation dialog only when a global flag has been set to "true". 想到的只有一种解决方案:仅在将全局标志设置为“ true”时才显示确认对话框。

if (ask_when_exiting == true)
 return "Your answers will be lost.";

You would have to set the variable to true? 您必须将变量设置为true? in the onclick event of every link that you want the confirmation to pop up for. 在您要弹出确认的每个链接的onclick事件中。 You should be able to mass apply this event to every link on your page using JQuery or another JS framework (Seomthing like $$('a').each().... ). 您应该能够使用JQuery或其他JS框架(例如$$('a').each().... )将事件大规模应用于页面上的每个链接。

However, this will disable the confirmation for reloading the page, or any other event that is not triggered using a control on the page like typing in another URL or closing the browser, as well. 但是,这将禁用对重新加载页面的确认,也不会禁用未使用页面上的控件(例如,键入另一个URL或关闭浏览器)触发的任何其他事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM