web前端 杭州-小白 javascript中beforeunload的使用
这个功能貌似用的地方很多额。。很多网站在你离开的时候都要询问你是否离开。貌似就是利用下面的方法做的。。挺不错的 。哈哈。。
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>beforeunload的使用</title>
</head>
<script type="text/javascript">
var goodexit=false;
function bindunbeforunload()
{
goodexit=false;
window.onbeforeunload=perforresult;
}
function unbindunbeforunload()
{
goodexit=true;
window.onbeforeunload=null;
}
function perforresult()
{
if(!goodexit)
{
return"当前操作未保存,如果你此时离开,所做操作信息将全部丢失,是否离开?";
}
}
</script>
<body>
<h1>test is start</h1>
<input type="button" value="绑定事件" id="btnBind" onclick="bindunbeforunload();" />
<input type="button" value="删除绑定事件" id="btnUnBind" onclick="unbindunbeforunload();" />
</body>
</html>
请看demo