简体   繁体   English

为什么在console.log 中不能显示keyCode?

[英]Why can't show the keyCode in console.log?

I want to show all keyCodes when you type some characters in the input tag.当您在输入标签中键入一些字符时,我想显示所有 keyCode。 ob is the input ,bind a function checkWord with event onkeydown , why console.log can't show its keycode value? ob 是输入,将函数checkWord与事件onkeydown绑定,为什么console.log无法显示其键码值?

 ob = window.document.getElementById("check"); function checkWord(){ console.log(onkeydown.keyCode); } ob.addEventListener("onkeydown",checkWord);
 <input id="check" type="text">

I want console.log to show 65 when I type a in the input tag.当我在输入标签中键入a时,我希望console.log显示65

Hmm you can do it like that:嗯,你可以这样做:

 // Getting Element const textInput = document.getElementById("textInput"); // Adding event listener textInput.addEventListener("keyup", event => { console.log(event.keyCode); });
 <input type="text" id="textInput">

In your code it would look like this:在您的代码中,它看起来像这样:

 const ob = document.getElementById("check"); ob.addEventListener("keydown",checkWord); function checkWord(event){ console.log(event.keyCode); }
 <input type="text" id="check">

This mainly did not work because you did use the wrong event name ( onkeydown -> keydown ) and you didn't pass the event to your function.这主要是行不通的,因为您确实使用了错误的事件名称( onkeydown -> keydown )并且您没有将事件传递给您的函数。

BTW: onkeydown exists but is used like that:顺便说一句: onkeydown存在,但使用方式如下:

object.onkeydown = function;

The difference between onkeydown and addEventLisener is that onkeydown is being defined once and with the event listeners you can add as meany to the same event as you want.之间的差别onkeydownaddEventLiseneronkeydown被定义一次,与事件监听器,你可以为米尼只要你想添加到同一事件。

// Adds listener
object.onkeydown = function0;
// Overwrites the old listener
object.onkeydown = function1;

// Add listener
object.addEventLisener("keydown", function0);
// Add another listener to the stack
object.addEventLisener("keydown", function1);

You have two issues你有两个问题

  • The event is named keydown .该事件名为keydown
  • keyCode is a property of the event that get's passed to your handler keyCode是传递给处理程序的event的属性

 ob = window.document.getElementById("check"); function checkWord(e){ console.log(e.keyCode); } ob.addEventListener("keydown",checkWord);
 <input id="check" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM