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

天涯浪子 提交于 2019-12-21 22:37:42

问题


I found a simple code on the internet a while ago... can't find the spesific site for it, but the code was made in 2005. So, I wondered if this was a good way of doing this:

This is in the HTML:

<body onload="document.body.focus();" onkeyup="return keypressed(event)">

When the key is up it calls this function in JavaScript:

function keypressed(e) {
    var intKey = (window.Event) ? e.which : e.keyCode;
    if (intKey == 13) { // 13 = enter key
        //something happens if the key is clicked
    }
        // here, you can add as many if sentences for key strokes as you want! (same as first)

return true;
}

What I mean is that the code is 7 years old (maybe more!) and I thought it might be a little or very outdated!

My questions:

  1. Is there a better way of doing this or is this still a good way? (I don't want to use jQuery for this code, because I don't want to use it just for one function)

  2. Do I really need this code: onload="document.body.focus();"? (I have not programmed this code, so I don't know.)


回答1:


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).




回答2:


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

Another way to do the same thing.



来源:https://stackoverflow.com/questions/11549051/detecting-which-key-is-pressed-is-this-a-good-way

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