在事件处理程序中访问事件对象 [英] Access event object in event handler
问题描述
当我尝试使用以下参数附加事件处理函数时:
When i try to attach event handler functions with parameters like :
myhandle.onclick = myfunction(param1,param2);
function myfunction(param1,param2){
}
现在我想在我的处理函数中访问事件对象。在网络上提到了一种发送事件对象的方法,例如:
Now I want to access the event object in my handler function. There is an approach mentioned on the web of sending event object, like:
myhandle.onclick = myfunction(event,param1,param2);
但是当我测试它时,它的给定事件对象是未定义的。
But its giving event object undefined when i test it out.
我知道库使这个东西变得简单,但我正在寻找原生的JS选项。
I know libraries make this stuff easy but I am looking for a native JS option.
推荐答案
我'我不完全确定你要做什么,但也许你正在寻找这样的东西?
I'm not entirely sure what you're trying to do, but perhaps something like this is what you're looking for?
function myfunction(param1, param2){
return function(event) {
// For compatibility with IE.
if (!event) {
event = window.event;
}
alert("event = " + event + ", param1 = " + param1 + ", param2 = " + param2);
};
}
myhandle.onclick = myfunction(param1, param2);
最终结果是 myfunction中的匿名函数
将被称为 onclick
处理程序,导致事件加上打印的两个参数。这两个参数在添加事件处理程序时是固定的,而每次用户点击 myhandle
事件都会更改>。
The end result of this is that the anonymous function inside of myfunction
will be called as the onclick
handler, resulting in the event plus the two parameters being printed. The two parameters are fixed at the time that the event handler is added while event
will change each time the user clicks on myhandle
.
这篇关于在事件处理程序中访问事件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!