[英]How can I capture keyboard events are from which keys?
I googled and got the following codes on the Net.However, when I press a keyboard key,it is not displaying me an alert box.我在网上搜索并获得了以下代码。但是,当我按下键盘键时,它没有向我显示警报框。 I want to get which character I have pressed in the alert box.
我想知道我在警告框中按下了哪个字符。 How do I fix this?
我该如何解决?
<script type="text/javascript">
var charfield=document.getElementById("char")
charfield.onkeydown=function(e){
var e=window.event || e;
alert(e.keyCode);
}
</script>
</head>
<body id="char">
</body>
</html>
If you want to get the character typed, you must use the keypress
event rather than the keydown
event.如果要输入字符,则必须使用
keypress
事件而不是keydown
事件。 Something like the following:类似于以下内容:
var charfield = document.getElementById("char");
charfield.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode > 0) {
alert("Typed character: " + String.fromCharCode(charCode));
}
};
try this jquery code试试这个 jquery 代码
$("body").keypress(function(e){
alert(e.which);
});
I can't off the top of my head think of a good situation in which to use the "on some event" method of a DOM element to deal with events on that element.我想不出一个好的情况,在这种情况下使用 DOM 元素的“on some event”方法来处理该元素上的事件。
The best practice is to use addEventListener
(or attachEvent
in older versions of Internet Explorer) like so:最佳做法是使用
addEventListener
(或旧版本 Internet Explorer 中的attachEvent
),如下所示:
charfield.addEventListener('keydown', function (e) { alert(e.keyCode); }, false);
If you want to account for attachEvent
as well:如果您还想考虑
attachEvent
:
(function (useListen) {
if (useListen) {
charfield.addEventListener('keydown', alertKeyCode, false);
} else {
charfield.attachEvent('onkeydown', alertKeyCode);
}
})(charfield.addEventListener);
function alertKeyCode(e) {
alert(e.keyCode);
}
You'll get the appropriate key code:您将获得相应的密钥代码:
charfield.onkeydown=function(evt){
var keyCode = (evt.which?evt.which:(evt.keyCode?evt.keyCode:0))
alert(keyCode);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.