Detecting which key is pressed - is this a good way?

巧了我就是萌 提交于 2019-12-04 15:44:18

You don't need the load handler, the page will be already focused after it loads, and/or if someone presses enter anywhere on the page it will be focused too.

If you need the keyup handler depends on what you'd like to do with it. The code you show is an enter handler. If you want a text input field to act on typing enter, it's more efficient to add the handler to that field.

Furthermore, it's better to do that from within your scripting (a part of unnobtrusive javascript usage). A keypress handler would be sufficient, because otherwise the enter value would become part of the input value. Something like:

[someTextInput].onkeypress = function(e){
  e = e || event;
  if ( (e.which || e.keyCode) === 13 ){
     // do things
  }
}

or you can use addEventListener/attachEvent (See here).

function displayunicode(e){
        var unicode = e.keyCode ? e.keyCode : e.charCode
        alert(unicode)
}

Another way to do the same thing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!