点此查看完整干净版本: IE里慎用onbeforeunload事件
中华图网
->
网页设计交流
->
IE里慎用onbeforeunload事件
登录
->
注册
->
回复主题
->
发表主题
越兔
2008-09-01 10:22
转于BL大哥BLOG:
http://www.never-online.net/blog/article.asp?id=237
以下例子,用的IE均是IE 8 beta1模拟IE7来测试的结果。
beforeunload和unload有什么区别呢?
看一下onbeforeunload和onunload的例子
Code:
<script type="text/javascript">//<![CDATA[
//http://www.never-online.net/blog/
window.onbeforeunload = function(e){
return 'leave or stay';
}
window.onunload = function(){
alert('onunload');
}
//]]></script>
[可以先修改代码再运行]
从上面的demo可以看出,
onbeforeunload事件在页面document对象发生变化的时候触发:包括刷新,关闭,前进,后退,主页这些按钮,js修改location.href,还有document.open之类的改变document对象的行为。而且可以让用户自己选择是否保持原页面不变化
unload是以onfeforeunload事件之后,且onbeforeunload返回的应该是true才可能触发unload事件
事实真的是我们想象的那样吗,请运行以下例子
Code:
<a href="javascript:;">点我一下</a>
<a href="javascript:alert('test');">点我一下</a>
<a href="###" onclick="alert('test');">点我一下</a>
<script type="text/javascript">//<![CDATA[
//http://www.never-online.net/blog/
window.onbeforeunload = function(e){
return 'leave or stay';
}
window.onunload = function(){
alert('onunload');
}
//]]></script>
[可以先修改代码再运行]
同时,请打开firefox,运行上面的面例子。可以简单得到结论。IE里,只要在a标签里锚点除外,都会触发onbeforeunload事件。不符合前边我们说到更改location.href会触发onbeforeunload事件的条件。
firefox的话就是正确的结果了,在本例中只有在离开时才触发这两个事件。
从这个例子可以得到些教训,不要在onbeforeunload写销毁对象的handler。
查看完整干净版本: IE里慎用onbeforeunload事件
Powered by
Cntuw.com
Time 0.023421 second(s),query:3 Gzip enabled
You can
|