当正在离开一个页面或正在卸载一个页面时,unload事件将会被激活,然而不管怎样,此事件不能够阻止页面的离开。
$(window).bind('unload',function(){});
从jquery 1.4起,你能够绑定beforeunload 事件给$(window) 对象来阻止页面的离开,卸载或导航到其它站点。
$(window).bind('beforeunload',function(){
return'';
});
随着beforeunload事件被绑定,当你关闭此页面,点击回退按钮或刷新此页面,一个确认提升框会被弹出,用来询问你是否真正想做。选择ok 用来离开页面,cancel 用来阻止页面的离开,使其保持在相同的页面。
另外 ,你被允许添加自己的学习到确认提示框(box)中:
$(window).bind('beforeunload',function(){
return'>>>>>Before You Go<<<<<<<< \n Your custom message go here';
});
注意beforeunload 事件是从jquery 1.4版本才开始支持的。
以下是完整代码
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<title>unload</title>
<script type="text/javascript" src="../jquery-1.11.1.min.js"></script>
</head>
<body>
<h1>stop a page from exit with jquery</h1>
<button id="reload">goto</button>
<script type="text/javascript">
$('#reload').click(function(){
window.location.assign("http://www.baidu.com/");});
$(window).bind('beforeunload',function(){
return '>>>>>你想去百度首页吗<<<<<<<< \n yes or no';
});
</script>
</body>
</html>
效果:
点击按钮前:
点击后:
最后点击离开此页:
如果点击留在此页,就会留在此页。