JavaScript before leaving the page

前端 未结 10 1897
谎友^
谎友^ 2020-11-22 08:01

I want to make a confirmation before user leaving the page. If he says ok then it would redirect to new page or cancel to leave. I tried to make it with onunload

<         


        
10条回答
  •  误落风尘
    2020-11-22 08:33

    This code when you also detect form state changed or not.

    $('#form').data('serialize',$('#form').serialize()); // On load save form current state
    
    $(window).bind('beforeunload', function(e){
        if($('#form').serialize()!=$('#form').data('serialize'))return true;
        else e=null; // i.e; if form state change show warning box, else don't show it.
    });
    

    You can Google JQuery Form Serialize function, this will collect all form inputs and save it in array. I guess this explain is enough :)

提交回复
热议问题