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

前端 未结 17 1602
深忆病人
深忆病人 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 02:45

    here is my html

    
    
    
    
    Home
    
    
    
     
        

    Welcome To My Home

    I am a student at Columbia College of Missouri.

    And so this is how I did something similar in javaScript

    var myGlobalNameHolder ="";
    
    function myFunction(){
    var myString = prompt("Enter a name", "Name Goes Here");
        myGlobalNameHolder = myString;
        if (myString != null) {
            document.getElementById("replaceME").innerHTML =
            "Hello " + myString + ". Welcome to my site";
    
            document.getElementById("belong").innerHTML =
            "A place you belong";
        }   
    }
    
    // create a function to pass our event too
    function myFunction2(event) {   
    // variable to make our event short and sweet
    var x=window.onbeforeunload;
    // logic to make the confirm and alert boxes
    if (confirm("Are you sure you want to leave my page?") == true) {
        x = alert("Thank you " + myGlobalNameHolder + " for visiting!");
    }
    }
    

提交回复
热议问题