JavaScript AddeventListener无参数工作

发布于 2025-02-10 15:38:37 字数 312 浏览 2 评论 0原文

我一直在寻找JavaScript文档,发现这是

const log = document.getElementById('log');

document.addEventListener('keydown', logKey);

function logKey(e) {
  log.textContent += ` ${e.code}`;
}

我不明白logkey函数在AddeventListener中的工作原理。当我按键时,控制台会打印其代码,但是LogKey在AddeventListener中没有任何参数。它是如何打印E.Code的?

I was looking for javascript documentation and found this

const log = document.getElementById('log');

document.addEventListener('keydown', logKey);

function logKey(e) {
  log.textContent += ` ${e.code}`;
}

I don't understand how logkey function is working in addeventlistener . when I press a key, the console prints its code but logkey is not having any parameters in addeventlistener. How did it print e.code ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

转身泪倾城 2025-02-17 15:38:37

您将功能作为参数传递给EventListener。 EventListener将logkey函数与事件一起以功能参数为单位。

在以下示例中,请参见如何将参数传递到该函数:

function func1(function_as_parameter){
  function_as_parameter('Shivam');
}

function helloWordFunction(name){
  console.log(`Hello ${name}!`);
}

func1(helloWordFunction); // Hello Shivam!
 

You pass the function as a parameter to the eventListener. The eventListener calls the logKey function with the event as a function parameter.

See in the following example how a parameter is passed on to the function:

function func1(function_as_parameter){
  function_as_parameter('Shivam');
}

function helloWordFunction(name){
  console.log(`Hello ${name}!`);
}

func1(helloWordFunction); // Hello Shivam!
 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文