$ (window) .keypress (function ()) not working in IE7?

This keypress event works fine for me in Chrome and Firefox, but just not used in IE7:

$(window).keypress(function(e) {
    alert('hello world');
});

Does anyone know alternatives for IE7?

Or is it the error above in my JavaScript, which means that it is not caught in IE7 - in this case, how can I debug it? I have script errors included in IE, but nothing appears.

+5
source share
4 answers

IE does not support key events on window.

Put it in place document.

$(document).keypress(function(e) {
    alert('hello world');
});
+26
source

IE7 , , $(document) $(window). - :

$(document).keypress(function(e) {
    alert("hello world");
});
+2

, :

1: document.onready, :

jQuery(function()
{
    $(window).keypress(function(e)....
});

, DOM .

2: :

jQuery(function()
{
    $("body").keypress(function(e)....
    $(document).keypress(function(e)....
});

( , , -, , - .)

-1

. , IE7 keyChar . , event.keyChar, . keyCode ascii keyChar, keycode , ... . , , , .

onkeydown
keyCode

myObject.kSave=-event.keyCode;

? , !!!

onkeypress
onkeypress , . onkeyup onkeypress , . , event.keyChar , 0. , IE7 event.keyChar, event.keyCode . (, , esc, tab ..) , . , , .

var ch = (event.keyChar == null) ? event.keyCode : event.keyChar;
if (ch >=32) {//ch is a character and not a control character
  myObject.kSave = ch; //tells onkeyup that the key was handled
  event.preventDefault(); //don't let default processing mess with your handler
  switch(ch) {
  //your character handler goes here
  }
} else if (ch > 0) {//ch is a control character
  event.preventDefault();
}

onkeyup
event.keyCode. , onkeypress , . , , onkeypress .

if (myObject.kSave+event.keyCode == 0) {//this is a special key or control character
  event.preventDefault();
  switch(event.keyCode) {
  //handle special keys here
  }
}

event.preventDefault(), , .

-2

All Articles