1
<input type="text"></input>

<script>
var a = document.getElementsByTagName('input')[0];
a.onkeypress = function(evt) {
  this.evt = evt || event;
var b = String.fromCharCode(evt.keyCode);
 while(forEach(evt) {
     alert("You pressed " + b);
   }
};
</script>

This doesn't seems to be working. It should always alert the key when user presses a key. The browser here is Chrome.

4

2 回答 2

2

It's not working because you're calling a function you don't define (forEach), here:

while(forEach(evt) {
//    ^

If you look in the JavaScript console, you'll see an error related to that.

Also, you don't want to assign to an evt property on this:

this.evt = evt || event; // <== Don't do this

Just use the argument:

evt = evt || event;

And there's no reason for a loop if you're going to alert every keypress individually.

Also, input elements don't have closing tags. It should just be:

<input type="text">

or (in XHTML, and optionally in HTML):

<input type="text"/>

not:

<input type="text"></input>

And finally, note that some browsers use which for the keycode, others use keyCode. You can use || to use whichever the browser supplies:

String.fromCharCode(evt.which || evt.keyCode)

Here's a minimal update: Live Copy | Live Source

<input type="text">
<script>
var a = document.getElementsByTagName('input')[0];
a.onkeypress = function(evt) {
  evt = evt || event;
  alert("You pressed " + String.fromCharCode(evt.which || evt.keyCode));
};
</script>
于 2013-05-30T08:58:19.427 回答
2

不需要while循环。只需以跨浏览器兼容的方式获取密钥,找到它的等效字符并警告它。

var a = document.getElementsByTagName('input')[0];
a.onkeypress = function(event) {
  //e.which & e.keyCode are for cross browser compliance
  alert(String.fromCharCode(event.keyCode || event.which)); 
};

工作示例 http://jsfiddle.net/VZEQe/

于 2013-05-30T09:00:33.947 回答