How to prompt users of unsaved changes if they try

2019-07-25 03:54发布

问题:

Possible Duplicate:
How do I stop a page from unloading (navigating away) in JS?
Prompt user for unsaved changes when leaving webpage

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).

Any help is much appreciated.

回答1:

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.';
};

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.



回答2:

Use unload method with "on" api of jquery.

 var flag = true; // set this var according to your use.
 $(window).on('beforeunload', function(){
     if(flag) {
        return "It looks like you have input you haven't submitted."
      }
 });