How does JavaScript recogize event object variables?

心已入冬 提交于 2019-12-10 20:18:46

问题


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>

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..)

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!


回答1:


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.

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

function (event) {
   // the inline code
}

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.

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.)

Happy coding!


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

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

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



来源:https://stackoverflow.com/questions/11265869/how-does-javascript-recogize-event-object-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!