定义JavaScript事件对象 [英] Defining JavaScript Event Object
问题描述
为什么我收到这条代码的错误?:
Why am I getting an error for this piece of code?:
function catchevent()
{
eventSrcID=(event.srcElement)?event.srcElement.id:'undefined';
eventtype=event.type;
status=eventSrcID+' has received a '+eventtype+' event.';
}
Firefox说事件
未定义。实际上,这是从这里复制的,它清楚地表明它适用于IE5。我在Ubuntu上使用Firefox 3.6.13。
Firefox says that event
is not defined. Actually, this is copied from here and it clearly says that it is for IE5. I use Firefox 3.6.13 on Ubuntu.
我的问题不是它在我的浏览器上不起作用的原因。相反,有没有办法定义事件
对象,如链接所示,对我的浏览器有效?
My Question is not why it doesn't work on my browser. Instead, is there a way to define event
object, as suggested by the link, that would work for my browser?
更新
为什么这不起作用
<html>
<head>
<script>
function catchevent( e ) {
// reference the proper event object
var e = e || window.event;
// reference the proper target
var srcElem = e.target || e.srcElement; //line no 9
// get the id of the target
var eventSrcID = srcElem.id;
alert(eventSrcID);
}
</script>
</head>
<body>
<a id="link1" href="#" onclick="catchevent()">link1</a>
<a id="link2" href="#" onclick="catchevent()">link2</a>
<a id="link3" href="#" onclick="catchevent()">link3</a>
</body>
</html>
对于这个我仍然在9号线上收到错误
For this i am still getting error on line no 9
e is undefined
[Break On This Error] var srcElem = e.target || e.srcElement;
现在我需要如何传递事件
对象 catchevent()
还是有错误?请建议。
Now how do I need to pass event
object on catchevent()
or is there some mistake? please suggest.
推荐答案
在Firefox和其他符合W3C标准的浏览器中,处理函数将接收一个事件对象作为函数的参数。
In Firefox and other W3C compliant browsers, the handler function will receive an event object as an argument to the function.
IE使用全局事件
对象。
这是针对您的代码的跨浏览器解决方案。
Here's a cross browser solution for your code.
function catchevent( e ) {
// reference the proper event object
var e = e || window.event;
// reference the proper target
var srcElem = e.target || e.srcElement;
// get the id of the target
var eventSrcID = srcElem.id;
// get the event type
var eventtype = e.type;
// create the status string
var status = eventSrcID + ' has received a ' + eventtype + ' event.';
}
你会注意到我使用了 var
创建变量时的关键字。你应该这样做,否则你就是在创建全局变量。
You'll notice I used the var
keyword when creating variables. You should do this, otherwise you're creating global variables.
另请注意关键字 this
将是一个对赋予处理程序的元素的引用。
Also note that the keyword this
will be a reference to the element to which the handler was assigned.
这篇关于定义JavaScript事件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!