当前位置: 首页 > 图文教程 > 网络编程 > Javascript > JavaScript获取事件对象的注意事项

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获取事件对象的注意事项


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

平时我们获取事件对象一般写法如下:

function getEvent(event) {
   
return event || window.event  // IE:window.event
}

如果没有参数,也可写成(非IE :事件对象会自动传递给对应的事件处理函数,且为第一个参数):

function getEvent() {
   
return arguments[0] || window.event // IE:window.event
}

这样的写法在除 Firefox(测试版本:3.0.12,下同) 外的浏览器上运行都不会有问题,但 Firefox 为什么例外呢?让我们这样一种情形:

<button id="btn" onclick="foo()">按钮</button>

<script>
function foo(){
   
var e =  getEvent();
   alert
(e);
}
</script>

运行结果在 Firefox 中是 undefined,为什么呢?

在 Firefox 中调用其实是这样的,先调用执行的是:

function foo(){
   
var e =  getEvent();
   alert
(e);
}

然后调用执行的是:

function onclick(event) {
    foo
();
}

会发现在 Firefox 下 onclick="foo()" 中的 foo() 无法自动传入事件对象参数,而默认传递给了系统生成的 onclick 函数,那本例我们可以通过 getEvent.caller.caller.arguments[0] 获得事件对象。

因此,我们的 getEvent 可以优化成(参照 yui_2.7.0b 中的 event/event-debug.js 中 getEvent 方法):

function getEvent(event) {
       
var ev = event || window.event;

       
if (!ev) {
               
var c = this.getEvent.caller;
               
while (c) {
                        ev
= c.arguments[0];
           
if (ev && (Event == ev.constructor || MouseEvent  == ev.constructor)) { //怿飞注:YUI 源码 BUG,ev.constructor 也可能是 MouseEvent,不一定是 Event
               
break;
           
}
            c
= c.caller;
               
}
       
}

       
return ev;
}

当然还有一个很简单的解决方法,就是手动将参数传递给 onclick="foo()"

<button id="btn" onclick="foo(event)">按钮</button>