怎么使用jquery阻止页面的离开或卸载

当正在离开一个页面或正在卸载一个页面时,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>

 

效果:

点击按钮前:


点击后:



最后点击离开此页:



如果点击留在此页,就会留在此页。


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值