There can be no Triumph without Loss,No Victory without Suffering,No Freedom without Sacrifice.
All you have to decide is what to do with the time that is given to you.
Get busy Living, or Get busy Dying?
  首页 | 留言给我 | 订阅 Rss | CLI | 黄白之恋 Posts:158   Hits: 5060441    Comments: 173    
 日历归档
<<  <  2024 - 04  >  >>
SuMoTuWeThFrSa
 123456
78910111213
14151617181920
21222324252627
282930
 About Me
 Name: ZhangSichu
 Sex: Male
 Age: 32
 Email: ZhangSichu@gmail.com
 MSN: ZhangSichu@hotmail.com
 Home: ZhangSichu.com
 WeiBo: weibo.com/zhangsichu
 个人推荐
 分类归档
  ·C++/C(5)  RSS
  ·软件工程(1)  RSS
  ·杂事/随感(26)  RSS
  ·.Net/Java(30)  RSS
  ·面向对象程序设计(5)  RSS
  ·汇编/破解(0)  RSS
  ·平面设计(3)  RSS
  ·SQL(5)  RSS
  ·COM/COM+(2)  RSS
  ·Web开发(81)  RSS
 My Friends
Back Forward Refresh Home 2024年4月19日 星期五 RSS CLI Mine Sweeper. In Javascript.

  FireFox下JavaScript全局Event对象
字体大小 [ ]

在IE下 JavaScript 中可以在任何地方使用全局的window.event来取得本次JavaScript被触发的Event,从而取得 KeyCode,EventSourceElement 等对象。而在FireFox中却没有这样的对象,如果有函数嵌套调用,需要不停的向下传递Event,例如下面的场景。
<div style="background-color:Red; width:300px; height:300px;" onclick="Test(event,this);" id="panel"></div>
function Test(event,dom){
Test1(event);
}

function Test1(event){
Test2(event);
}

function Test2(event){
alert(event.target.id);
}

在Test2方法中需要使用event,就需要写成这样。如果在某种场景下,比如添加新功能,需要修改原来的Test2方法,需要访问event对象,而原来Test2方法的签名是Test2(),没有参数event,这时需要修改Test2()为Test2(event) 十分的不美观,虽然JavaScript这样的修改,是方法的重载,但是也破坏了原来的方法签名。
在FireFox中是否有window.event这样的全局变量来获取event?
不幸的是FireFox的对象模型中是没有的,但是可以使用变通的方法取得。例如:
function GetEvent(caller){
if(document.all)
return window.event; //For IE.
if(caller == null || typeof(caller) != "function")
return null;
while(caller.caller != null){
caller = caller.caller;
}
return caller.arguments[0];
}

这里使用document.all判断是否是IE浏览器的做法是不好的,应该使用UserAgent来判断,JQuery等类库中有好的实现。
这样上面的 Test2方法就可以不用修改方法签名了:
function Test2(){
var event = GetEvent(Test2);
alert(GetEventTarget(event).id);
}
function GetEventTarget(event){
if(document.all)
return event.srcElement;
return event.target;
}

为什么可以写出GetEvent方法,取得Event?
因为在Firefox的事件模型中最初的事件调用是将event显示的传递给方法的,所以可以写出GetEvent方法,取得唤起JavaScript的event。

Click to Open in New Window
  Posted @ 2/3/2009 12:37:08 PM | Hits (6918) | Comment (0

  Post Comment
标题 *
作者 *
密码 记住我
评论 *
    


Stable in Firefox 1.5 2.0Stable in IE6 IE7Stable in MozillaStable in Netscape
ZhangSichu.com V0.1.7507
Powered By ZhangSichu
Copyright © ZhangSichu
Download ZhangSichu.com source code. Download source code