问题
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:
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)
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