开发者

Yes/No box in Javascript like this one here in StackOverflow?

I want to know how can I display a 开发者_如何学运维confirmation box when the users try to get out of the page, like this one here in StackOverflow when you try to close the "Ask Question" page.

Thanks you in advance.


Actually, all that is necessary is this:

window.onbeforeunload = function(){ return "You should save your stuff."; }

This is also kind of a dupe of this: How to show the "Are you sure you want to navigate away from this page?" when changes committed?


In javascript, attach a function to window.onbeforeunload, like so:

window.unbeforeunload = function (e)
{
    // return (prompt ('Are you sure you want to exit?'));

    // EDIT: Amended version below: 
    var e = e || window.event;
    if (e) e.returnValue = 'Your exit prompt';
    return 'Your exit prompt';
}

EDIT: As the comments below indicate, I had misunderstood the working of the event. It should now work as intended.

Ref: window.onbeforeunload (MDC)


probably a dupe: How do you prevent a webpage from navigating away in JavaScript?, but you can do this by adding an delegate to the window.onbeforeunload event

<script type="text/javascript">
   window.onbeforeunload = function() {
      //will show a dialog asking the user if 
      //they want to navigate away from the current page
      // ok will cause the navigation to continue, 
      // cancel will cause the user to remain on the current page
      return "Use this text to direct the user to take action.";
   }
</script>

Update: doh! updated code to do what the OP really wanted :D


You want to catch the onbeforeunload event of window. Then if you return a string, the browser will display your message in a prompt. Here's an article with sample code.


You can use the window.onbeforeunload event to catch this. If there is any value inside the textarea then an alert message is shown.


That's browser based.

As long as you implement <form> tag, and you type in something in the form, and in Google Chrome, it will prompt you that message.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜