当前位置: 首页 > 图文教程 > 网络编程 > Javascript > FireFox JavaScript全局Event对象

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 中的 FireFox JavaScript全局Event对象


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

在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