如果他们尝试离开网页,如何提示用户未保存的更改 [英] How to prompt users of unsaved changes if they try to leave the webpage

查看:382
本文介绍了如果他们尝试离开网页,如何提示用户未保存的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何在JS中停止卸载页面(导航)?

离开网页时为未保存的更改提醒用户

我有一个在Dreamweaver中设计的只包含文本字段的PHP表单,它从我的数据库中一次检索一个记录。我在此页面上还有一个更新记录按钮,当单击时,更新数据库记录,并对表单中的数据进行任何更改。我想要的是,如果用户以某种方式编辑表单数据,并尝试离开页面而不点击更新记录按钮,则会提示该页面包含未保存的更改,并且将要求他们验证是否要离开或者不是(可能通过一些javasript,如果可能的话)。

I have a php form which i designed in dreamweaver containing only text fields, which retrieves a single record at a time from my database. I have on this page also an 'update record' button which when clicked updates the database record with any changes that was made to the data in the form. I want that if a user edits form data in some way and tries to leave the page without clicking the 'update record' button, that they would be prompted that the page contains unsaved changes and they would be asked to verify if they want to leave or not (maybe via some javasript if possible).

非常感谢任何帮助。

推荐答案

onbeforeunload 在导航实际开始之前触发,你可以使用一种相当独特的方法来停止导航:只需返回一个对话框中显示的字符串,浏览器会询问用户是否真的希望离开该页面。

onbeforeunload fires before navigation actually begins, and you can stop the navigation using a rather unique method: simply return the string you'd like displayed in a dialog, and the browser will ask whether or not the user really wants to leave the page.

如果不返回一个字符串,浏览器会继续正常导航。您可以使用此行为,例如,仅在用户有未保存的更改时才显示提示。

If you don't return a string, the browser continues navigation normally. You could use this behavior, for example, to only show a prompt if the user has unsaved changes.

window.onbeforeunload = function(e) {
    if (unsavedChanges) return 'Dialog text here.';
};

只能通过返回字符串并让浏览器提示停止导航。 alert 确认实际上是禁止在 onbeforeunload 中,在 onunload 中,您没有实际停止导航的功能。

You can only stop navigation by returning a string and letting the browser prompt. Calling alert or confirm is actually prohibited in onbeforeunload, and in onunload, you have no facility to actually stop navigation.

这篇关于如果他们尝试离开网页,如何提示用户未保存的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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