Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

html - Javascript onload and onunload

Consider the following HTML snippet containing some javascript utilizing prompt and unload. The prompt() method works fine but I want alerting something like Goodbye, user when reloading or leaving the page. Any help is greatly appreciated.

<body onload="promptName()" >


        <script type="text/javascript">
        function promptName()
        {
            var userName = prompt("What's your name ?", "")
            return userName;
        }

        function goodBye()
        {
            alert("Goodbye, " + promptName() + "!");
        }

        window.onunload = goodBye();

        </script>

  </body>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should write it like this:

window.onunload = goodBye;

Also, you might consider using the onbeforeunload event in some browsers:

window.onbeforeunload = goodBye;

When you write window.onunload = goodBye(); you assign whatever handler that is returned from goodBye to the unload event. Since nothing is returned, there will be no event handler. You need to reference the function instead: window.onunload = goodBye;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...