0
function checkEnter(event) { 
    var charcode; 
    if (event && event.which) { 
     charcode = event.which; 
     alert("Case 1. event.which is " + charcode); 
    } 

    else if (event && !event.which) { 
     charcode = event.keyCode; 
     alert("Case 2. event.keyCode is " + charcode); 
    } 

    document.getElementById("text1").value=""; 
} 

<input type="text" id="text1" onkeyup="checkEnter(event)" />IE에서 onkeydown이 제대로 작동하지 않는 이유는 무엇입니까?

위의 기능은 IE7와 크롬 모두에서 작동합니다.

<input type="button" id="button1" onclick="checkKeyPressed(event)" value="Button" />

function checkKeyPressed() { 
    document.onkeydown = function(event) { 
     var charcode; 
     if (event && event.which) { 
      charcode = event.which; 
      alert("charcode is " + charcode); 
     } 

     else if (event && !event.which) { 
      charcode = event.keyCode; 
      alert("charcode (keyCode) is " + charcode); 
     } 
    } 
} 
그러나 이것에만 크롬에서 작동합니다. 왜 그런가?

+1

? IE는 약간의 "특별한" –

+0

키를 입력했기 때문에 모든 키에 대해이 이벤트를 발생시키지 않습니다. 하지만 그것은 첫 번째 작품, 그래서 이상한 일종의. – Fabian

답변

0

문제가 해결되었습니다. 분명히 onkeydown()에서 "event"매개 변수를 제거하면됩니다. 나는 IE가 크롬이하는 것처럼 자바 스크립트를 읽지 않기 때문에 매개 변수가 전달되지 않았기 때문에 제대로 작동하지 않는다고 생각한다. =. =

1

매개 변수가 정의되지 않았는지 단순히 확인하여 두 매개 변수를 결합 할 수 있습니다.

function MyOnClick(oEvent) 
{ 
    if (typeof(oEvent) == "undefined") 
    oEvent = event; 

    // continue with your code 
} 

이 파이어 폭스, 크롬, IE 위해 작동 등

당신이 타격 키
관련 문제