[javascript] Question when receiving an event as a factor for the function

Asked 2 years ago, Updated 2 years ago, 111 views

Hello. The link below is the calculator code I made.

Calculator source code

html : <button id="1" onclick="input.getStr()">1</button>

JS : input.getStr = function() { var str = event.target.id; }

The input.getStr function is a function that receives the number you click on when you click on the number in the calculator. Even though I didn't declare function(event){}, I got event.target.

Question 1) Even if the event object is not included as a factor of the function below, input.getStr = function() { var str = event.target.id; } Is the event object delivered as a parameter to the event handler? (Otherwise, the event object seems to always pass because the value cannot enter event.target.)

Q2) I would like to ask if there is a difference between when you put the event in the parameter and when you don't. <Button onclick="input.getStr(event)">1</button> when writing input.getStr = function(event) { You have to write var str = event.target.id;}.

Thank you!

javascript event

2022-09-22 18:08

1 Answers

When using an event handler function, such as GlobalEventHandlers.onclick(), there are some 'browsers' that allow you to use event variables inside the function without any parameters in the function declaration. This method is not recommended because it is non-standard with different browsers.

Supplementary Description:

<button id="myBtn" onclick="handleClick(e)">1</button>

If you look at the onclick property above, it is shown below.

function handleClick(e) {
   console.log(e.target.tagName); // BUTTON
}

var btn = document.getElementById('myBtn');
btn.onclick = handleClick;

When a click event occurs, a function assigned to the onclick property of the button tag is executed by the implementation (where it will be a browser, right?). The Event object is passed as the only parameter. We're just naming the object e in this example.


2022-09-22 18:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.