当前位置: 首页 > 图文教程 > 网络编程 > Javascript > javascript Onunload与Onbeforeunload使用小结

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 javascript Onunload与Onbeforeunload使用小结


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-10   浏览: 336 ::
收藏到网摘: n/a

Onunload,onbeforeunload都是在刷新或关闭时调用,可以在<script>脚本中通过window.onunload来指定或者在<body>里指定。区别在于onbeforeunload在onunload之前执行,它还可以阻止onunload的执行。 Onbeforeunload也是在页面刷新或关闭时调用,Onbeforeunload是正要去服务器读取新的页面时调用,此时还没开始读取;而onunload则已经从服务器上读到了需要加载的新的页面,在即将替换掉当前页面时调用。Onunload是无法阻止页面的更新和关闭的。而Onbeforeunload 可以做到。曾经做一个考试系统,涉及到防止用户半途退出考试(有意或者无意),代码如下:
复制代码 代码如下:

<body onbeforeunload=" checkLeave()">
<script>
function checkLeave(){
event.returnValue="确定放弃考试?(考试作废,不记录成绩)";
}
</script>

这样可以让用户确认是否要退出考场,其实BLOGJAVA在用户编写BLOG时,如果不保存而跳转到其他页面,也会有一个确认的提示(防止误操作),也是用到Onbeforeunload。
另外还可以用来在页面关闭的时候关闭session,代码如下(注:用window.screenLeft > 10000 来区分关闭和刷新操作):
复制代码 代码如下:

<body onbeforeunload=" closeSession()">
<script>
function closeSession (){
//关闭(刷新的时候不关闭Session)
if(window.screenLeft>10000){
//关闭Session的操作(可以运用AJAX)
}
}
</script>