页面关闭beforeunload事件

来源:互联网 发布:手写记事本软件 编辑:程序博客网 时间:2024/05/17 06:24

beforeunload事件在当页面卸载(关闭)或刷新时调用,事件触发的时候弹出一个有确定和取消的对话框,确定则离开页面,取消则继续待在本页;

jquery离开页面弹出提示代码

//绑定beforeunload事件
$(window).bind('beforeunload',function(){
return '您输入的内容尚未保存,确定离开此页面吗?';
});
//解除绑定,一般放在提交触发事件中
$(window).unbind('beforeunload');
js离开页面提示  onbeforeunload事件方法

window.onbeforeunload = function(event) { 

return confirm("确定退出吗"); 

}

以下操作触发beforeunload,onbeforeunload
1 ·关闭浏览器窗口 
2·通过地址栏或收藏夹前往其他页面的时候 
3·点击返回,前进,刷新,主页其中一个的时候 
4·点击 一个前往其他页面的url连接的时候 
5·调用以下任意一个事件的时候:click,document.write()方法(输出内容),document.open()  打开一个新的空白文档,document.close()方法可关闭一个由open()方法打开的输出流,并显示选定的数据。
,window close (),form.submit. 
6·当用window open打开一个页面,并把本页的window的名字传给要打开的页面的时候。
 7·重新赋予location.href的值的时候。
 8·通过input type=”submit”按钮提交一个具有指定action的表单的时候。
 9.可以用在以下元素:body, frameset, window
 
// 关闭窗口时弹出确认提示
$(window).bind('beforeunload', function(){
    // 只有在标识变量is_confirm不为false时,才弹出确认提示
    if(window.is_confirm !== false){     
           return '您可能有数据没有保存';
    }
});
// 提交表单时,不弹出确认提示框
$('form').bind('submit', function(){   
          is_confirm = true; 
 });
//页面内的跳转操作均不弹出确认窗口
$(window).bind('mouseover mouseleave', function(event){
    is_confirm = event.type == 'mouseleave';
});
(function(){   
     // 关闭窗口时弹出确认提示   
    $(window).bind('beforeunload', function(){     
   // 只有在标识变量is_confirm不为false时,才弹出确认提示     
    if(window.is_confirm !== false)     
          return '您可能有数据没有保存'; 
    }) 
  // mouseleave mouseover事件也可以注册在body、外层容器等元素上 
   .bind('mouseover mouseleave', function(event){   
      is_confirm = event.type == 'mouseleave';   
    });
})();
 
<script type="text/javascript">
var changeFlag=false;
//标识文本框值是否改变,为true,标识已变 
$(document).ready(function(){
//文本框值改变即触发 
$("input[type='text']").change(function(){
changeFlag=true; 
}); 
//文本域改变即触发
$("textarea").change(function(){
changeFlag=true; 
}); 
});

//离开页面时保存文档 
window.onbeforeunload = function() {
  if(changeFlag ==true){
    //如果changeFlag的值为true则提示 
  if(confirm("页面值已经修改,是否要保存?")){
    //处理信息保存...
      alert("即将执行保存操作...");
  }else{
    //不保存数据...
    alert("不保存信息...");
  }
}

转载地址:
http://www.cnblogs.com/hudandan/p/5960875.html
原创粉丝点击