Home>

Please write your question in detail here.
-I want to input a character string in input and press enter so that the next input will be focused.
-Before realizing the above operation, I tried to display'Key Down'on the console by pressing any key while focusing on input for the time being.

I get a message on the console 20 times, even though I haven't pressed any keys.

Corresponding source code
<! DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0">
<title>Text Edit</title>
<link rel = "stylesheet" href = "styles.css">
</head>
<body>
   
<script src = "main.js"></script>
</body>
</html>
'use strict';
function createInput () {
    const input = document.createElement ('input');
    input.type ='text';
    input.addEventListener ('keydown', console.log ('Key Down'))
    document.getElementById ('content'). appendChild (input)
}
for (let i = 0;i<20;i ++) {
    createInput ();
}
What I tried

・ I changed the event to click or focus. I wondered if it was related to pressing command + r on the page reload.
→ Even if you change the event, the message is displayed when the page is loaded.
The event seems to be ignored, but I don't know how to solve it.

-Re-examined the meaning of event-related terms such as event handlers.
→ I learned this, but this problem has not been solved.

Supplementary information (FW/tool version, etc.)

Please provide more detailed information here.

  • Answer # 1

    Specify a function object in the second argument of addEventListener.

      input.addEventListener ('keydown', function (event) {console.log ('Key Down')});
      input.addEventListener ('keydown', event =>console.log ('Key Down'));

    Such.

    afterwards,createInputIf you call only once, the event listener will be set up so that console.log will be called every time you type a character into input.