在我们编写文章或者是写日志的时候,可能会不小心点击到其它链接,跳转到其它页面,导致我们写的东西没有保存,这是一个很大的损失,其实可以使用 onbeforeunload 事件来避免这样的事情发生,这也是提高用户体验的一个方法。
onbeforeunload 事件可以直接写在 body 的标签里面,像这样:
<body onbeforeunload="return '温馨提醒:\n这些对您来说【非常重要】,建议点击【留在此页】';">
也可以自定义函数调用方法,这种方法更方便编写代码,所以也推荐大家使用这个方法:
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = '确定退出吗?ss';
}
// For Safari
return '确定退出吗?ss';
};
例如我们要在一个表单提交以前,防止用户因为误操作而跳转页面导致编写的内容丢失,我们可以这样编写代码:
<form id='YourFormId' action=''>
<input type="button" name="button" id="button" value="提交" onclick="sumbit();"/>
</form>
var is_submit = false;
window.onbeforeunload=function checkLeave(e){
e = e || window.event; //此方法为了在firefox中的兼容
if(!is_submit){
e.returnValue='离开会使编写的内容丢失。';
}
}
//提交表单
function sumbit(){
is_submit = true;
document.getElementById('YourFormId').submit();
}
代码说明:

