JavaScript如何识别事件对象变量? [英] How does JavaScript recogize event object variables?

查看:84
本文介绍了JavaScript如何识别事件对象变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于JavaScript事件对象的快速问题 - 当我尝试将事件变量传递给函数时,JavaScript如何知道?例如,当我像这样定义一个onclick处理程序时:

Quick question about JavaScript event objects - how does JavaScript know when I'm trying to pass an event variable to a function? For example, when I define an onclick handler like so:

<button onclick='SendMessage(event)'></button>

JavaScript是否因为我将其命名为event而传递事件变量?如果是这样,为了传递事件变量,它保留了哪些其他变量名? (e?ev?etc ..)

does JavaScript pass the event variable just because I named it "event"? If so, what other variable names does it reserve for the purpose of passing event variables? (e? ev? etc..)

如果是这种情况,可以通过命名本地或全局变量event,e等来涵盖它们。 。?

If this is the case, can they be covered by naming local or global variables "event", "e", etc.. ?

提前感谢您满足我的好奇心!

Thanks in advance for satisfying my curiosity!

推荐答案

必须在内联事件中被称为事件事件 是一个关键字,并且不是 JavaScript中的保留字;它只是早期Netscape工程师决定的变量名。

It must be called event in an inline event. event is not a keyword and is not a reserved word in JavaScript; it is merely the variable name the early Netscape engineers decided upon.

为事件提供的内联文本实际上是包裹 1 as:

The inline text supplied for the event is effectively wrapped 1 as:

function (event) {
   // the inline code
}

IE使用 window.event 属性来传递事件信息,但名称重合,所以使用事件将适当地回退正常的JavaScript变量分辨率。

IE uses the window.event property to pass event information, but the names coincide so using event will fallback through the normal JavaScript variable resolution as appropriate.

当然,如果直接附加函数对象,那么事件变量,因为它只是第一个参数,可以命名为任何所需的。不幸的是IE的 window.event 方法也必须处理,并且调用参数 event 不能解决它。

Of course, if attaching a function object directly then the event variable, because it's just the first parameter, can be named whatever is desired. Unfortunately IE's window.event approach must be dealt with as well, and calling the argument event doesn't address it.

elm.onclick = function (my_event_name) {
    my_event_name ||= window.event // for IE
    ...
}

(我建议尽可能避免使用内联事件并使用统一/简化事件的库。)

(I would recommend avoiding inline events as much as possible and using a library that unifies/simplifies events.)

快乐编码!

1 此行为详情请参阅 HTML 5:事件处理程序,事件处理程序内容属性

1 This behavior is covered in detail in HTML 5: Event Handlers, Event handler content attributes:


[内联事件,例如onclick,text]必须包含有效的JavaScript代码,在解析时,它将匹配[函数]生产。 。

[inline event, e.g onclick, text] must contain valid JavaScript code which, when parsed, would match [a function] production ..

使用脚本执行环境上面创建的onment,创建一个函数对象。让函数有一个名为event 的参数。

Using the script execution environment created above, create a function object .. Let the function have a single argument called event.

这篇关于JavaScript如何识别事件对象变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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