最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - element onkeydown keycode javascript - Stack Overflow

programmeradmin0浏览0评论

I am using this code snippet to add KeyDown event handler to any element in the html form

for(var i=0;i<ele.length;i++)
{
    ele[i].onkeydown = function()
    {
            alert('onkeydown');
    } 
}

How can I know which key has been pressed on keydown event? I try this

for(var i=0;i<ele.length;i++)
{
    ele[i].onkeydown = function(e)
    {
           alert(e.KeyCode);
    } 
}

but it is not working, why? Thanks a lot

I am using this code snippet to add KeyDown event handler to any element in the html form

for(var i=0;i<ele.length;i++)
{
    ele[i].onkeydown = function()
    {
            alert('onkeydown');
    } 
}

How can I know which key has been pressed on keydown event? I try this

for(var i=0;i<ele.length;i++)
{
    ele[i].onkeydown = function(e)
    {
           alert(e.KeyCode);
    } 
}

but it is not working, why? Thanks a lot

Share Improve this question asked Oct 27, 2009 at 10:30 Arsen MkrtchyanArsen Mkrtchyan 50.7k33 gold badges154 silver badges187 bronze badges 3
  • What are you trying to do? Are you trying to detect printable characters or other keys? For the former you should handle the keypress event, for the latter it's keydown. – Tim Down Commented Oct 27, 2009 at 11:02
  • I want to change 'enter' press to 'tab' – Arsen Mkrtchyan Commented Oct 27, 2009 at 11:33
  • KeyCode should be keyCode document.onkeydown = function(e){alert(String(e.keyCode));} Worked for me – partizanos Commented Feb 9, 2016 at 19:41
Add a comment  | 

4 Answers 4

Reset to default 6

This is the code I use for this problem. It works in every browser.

//handle "keypress" for all "real characters"     
if (event.type == "keydown") {
    //some browsers support evt.charCode, some only evt.keyCode
   if (event.charCode) {
      var charCode = event.charCode;
   }
   else {
      var charCode = event.keyCode;
   }
}

For detecting Enter, you could use the following code, which will work in all mainstream browsers. It uses the keypress event rather than keydown because Enter produces a printable character:

ele[i].onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.keyCode || evt.which;
    if (charCode == 13) {
        alert("Enter");
        // Do stuff here
    }
};

I used this:

function check(){
 if (event.keyCode == 32){
  alert("Space is pressed");
 }
}

and in my body tag: onKeyPress="check()"

It is keyCode, not KeyCode.

发布评论

评论列表(0)

  1. 暂无评论