我们实现在刷新或关闭前弹出弹框显示提示文字很容易,例:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="renderer" content="webkit">
<title>test</title>
<script type="text/javascript" src="skin/base2/js/jquery-1.11.3.min.js"></script>
</head>
<body>
</body>
<script>
;$(function() {
$(window).on('beforeunload', function() {
return "您确定要离开吗?!";
});
});
</script>
</html>
如果我们想要实现在刷新或关闭前调用某个方法就不行了,也许很多人尝试过了,使用如下方法:
$(window).on('beforeunload', function() {
alert(1);
});
可是这种方法只在ie浏览器有效果。
解释:
1 其实beforeunload是起了作用的,只不过alert()弹框在浏览器中没有出现
2 测试这个,我们可以对后台发送请求,看看后台数据是否发生变化
3 beforeunload在ff中不兼容,我们同时可以加上unload事件(这两个事件的具体区别大家可以自行百度)
测试思路:
$(window).on('beforeunload unload', function() {
$.ajax({
//发送请求,刷新一次,后台数据自增一次,大家查看后台数据就知道了,这两个事件是起了作用的
});
});