Why do you have to pass the event object as a parameter?

后端 未结 5 1436
没有蜡笔的小新
没有蜡笔的小新 2020-12-28 10:37

I\'m learning how to manipulate events in JavaScript and I\'m wondering \"why do you have to pass the event object as a parameter (argument) into a function when using event

5条回答
  •  礼貌的吻别
    2020-12-28 10:52

    Simply put, the Event object passed to a handler contains details about the event. For example, a KeyboardEvent contain info about the key pressed, the corresponding character, and any modifier keys (alt, shift, control, meta) that were held down.

    Does the event handler try to pass in an event before it gets assigned or?

    The handler is your function, so it's the receiver of event, not the passer.

    • The event handler is bound when you assign it to the element's onclick property (or by calling addEventListener, the modern, preferred method), which is before the handler is invoked.
    • The Event object is passed when the handler is invoked, which is when the event fires.

    So, when a user clicks on your #button_1, this causes a "click" event to fire on the button, which invokes the button's "click" handler, which is passed a MouseEvent.

    For more information, read about event-driven programming.

提交回复
热议问题