我知道有很多问题,但没有什么是回答我的权利.当用户离开页面时,我想显示确认对话框.如果用户按取消,他将留在页面上,如果确定,他所做的更改将通过调用方法进行回滚.我这样做:
- window.onbeforeunload = function () {
- var r = confirm( "Do you want to leave?" );
- if (r == true) {
- //I will call my method
- }
- else {
- return false;
- }
- };
问题是我得到浏览器默认的弹出窗口:“LeavePage / StayOnPage”
This page is asking you to confirm that you want to leave – data you
have entered may not be saved.
这个消息显示在Firefox中,在Chrome中有所不同.在我的第一个确认对话框上按OK后,我得到这个弹出窗口.
解决方法
这是我做了什么,修改以适应您的需要:
- // This default onbeforeunload event
- window.onbeforeunload = function(){
- return "Do you want to leave?"
- }
- // A jQuery event (I think),which is triggered after "onbeforeunload"
- $(window).unload(function(){
- //I will call my method
- });
注意:它已经过测试,可以在Google Chrome,IE8和IE10上工作.