javascript 事件处理程序中的“事件"参数来自哪里? [英] Where does the 'event' param come from in javascript event handlers?

查看:26
本文介绍了javascript 事件处理程序中的“事件"参数来自哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常看到 javascript 代码,其中动态分配事件处理程序(如 onmousemove).示例:

document.getElementById('foo').onmousemove = function(e){/* 用事件 e 做一些事情 */}

显然这个e"参数是某种事件对象.这是从哪里来的,例如:在调用函数时,谁或什么定义了这个e"参数是什么,我也可以在静态 html 中执行此操作吗?我的意思是这样的:

... </div>

我应该为e"填写什么才能获得相同的事件?我也可以将它与更多参数结合起来,比如

... </div>

再次,e 应该是事件对象吗?

解决方案

事件对象存储在任何事件处理程序内部的 window.event 中,因此您无需担心您的处理程序是否符合接受它作为参数.

在您的第二个和第三个示例中,e 参数将作为未定义传递,因为该范围内不存在变量 e(除非您有全局 e).

Often I see javascript code where event handlers (like onmousemove) are assigned dynamically. Example:

document.getElementById('foo').onmousemove = function(e)
{ /* do some stuff with event e */ }

Apparently this 'e' parameter is some kind of event object. Where does that come from, as in: who or what defines what this 'e' parameter is when the function is called, and can I also do this in static html? I mean like this:

<div id='foo' onmousemove='Bla(e)'> ... </div>

What should I fill in for 'e' to get that same event thing? And can I also combine that with more parameters, like

<div id='foo' onmousemove='Bla(this,e,4)'> ... </div>

where e is, again, supposed to be the event object?

解决方案

The event object is stored in window.event inside of any event handler, so you do not need to worry about your handler conforming to accepting it as a parameter.

In your second and third examples, the e parameter will be passed as undefined because no variable e exists in that scope (unless you have a global e).

这篇关于javascript 事件处理程序中的“事件"参数来自哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆