How to show the “Are you sure you want to navigate away from this page?” when changes committed?

前端 未结 17 1784
深忆病人
深忆病人 2020-11-22 02:11

Here in stackoverflow, if you started to make changes then you attempt to navigate away from the page, a javascript confirm button shows up and asks: \"Are you sure you want

17条回答
  •  一向
    一向 (楼主)
    2020-11-22 03:05

    To expand on Keith's already amazing answer:

    Custom warning messages

    To allow custom warning messages, you can wrap it in a function like this:

    function preventNavigation(message) {
        var confirmOnPageExit = function (e) {
            // If we haven't been passed the event get the window.event
            e = e || window.event;
    
            // For IE6-8 and Firefox prior to version 4
            if (e)
            {
                e.returnValue = message;
            }
    
            // For Chrome, Safari, IE8+ and Opera 12+
            return message;
        };
        window.onbeforeunload = confirmOnPageExit;
    }
    

    Then just call that function with your custom message:

    preventNavigation("Baby, please don't go!!!");
    

    Enabling navigation again

    To re-enable navigation, all you need to do is set window.onbeforeunload to null. Here it is, wrapped in a neat little function that can be called anywhere:

    function enableNavigation() {
        window.onbeforeunload = null;
    }
    

    Using jQuery to bind this to form elements

    If using jQuery, this can easily be bound to all of the elements of a form like this:

    $("#yourForm :input").change(function() {
        preventNavigation("You have not saved the form. Any \
            changes will be lost if you leave this page.");
    });
    

    Then to allow the form to be submitted:

    $("#yourForm").on("submit", function(event) {
        enableNavigation();
    });
    

    Dynamically-modified forms:

    preventNavigation() and enableNavigation() can be bound to any other functions as needed, such as dynamically modifying a form, or clicking on a button that sends an AJAX request. I did this by adding a hidden input element to the form:

    
    

    Then any time I want to prevent the user from navigating away, I trigger the change on that input to make sure that preventNavigation() gets executed:

    function somethingThatModifiesAFormDynamically() {
    
        // Do something that modifies a form
    
        // ...
        $("#dummy_input").trigger("change");
        // ...
    }
    

提交回复
热议问题