大众世界 world of demotic + 社区新动力

 找回密码
 注册会员
搜索
查看: 1776|回复: 0

[Javascript] 页面关闭beforeunload事件

[复制链接]
发表于 2019-6-24 16:00:15 | 显示全部楼层 |阅读模式

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("不保存信息...");
  }
}
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册会员

本版积分规则

Archiver|手机版|小黑屋|Wod Inc. ( 蜀ICP备20000008号-8

GMT+8, 2026-4-2 03:13 , Processed in 0.106295 second(s), 28 queries .

Powered by Discuz! X3.4

Copyright © 2001-2026 Tencent Cloud.

快速回复 返回顶部 返回列表