开发者

Key event not firing

开发者 https://www.devze.com 2023-04-05 09:27 出处:网络
My Javascript: $(\"#test\").keypress(function(e){ if (document.all){ var evt = event.keyCode; } else if(e.which) { var evt = e.which;}

My Javascript:

$("#test").keypress(function(e){
       if (document.all){ var evt = event.keyCode; }
       else if(e.which) { var evt = e.which;       }           
       else             { var evt = e.charCode;    }

       if (evt == 13){ // with any other key, the alert d开发者_运维技巧os not fire
            alert(evt);
       }
       return true;
});

Jsfiddle demo

The keycode 13 Enter fires the alert, but any other dosent.

Can any one tell me why?

I need to verify if the 13 or 9 tab was fired.

Thanks.


Use keydown rather than keypress

$('#test').live('keydown', function(e) { 
    var k = e.keyCode || e.which; 

    if (k == 9 || k == 13) { 
        e.preventDefault();
        alert(k);
    } 
});

working: http://jsfiddle.net/hunter/cDVek/15/


add a conditional clause to check for evt == 9:

if (evt == 13) { 
   alert(evt); 
} else if (evt == 9) { 
   alert(evt);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号