开发者

Why doesn't onkeydown working properly on IE?

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)" />

The above function works on both IE7 and Chrome.

function checkKeyPressed() {
    document.onkeydown = function(event) {
        var charcode;
        if (event && event.which) {
            charcode = event.which;
            alert("charcode is " +开发者_C百科 charcode);
        }

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

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

However this one works only in Chrome. Any idea why?


You can combine the two by simply checking to see if the parameter is undefined.

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

  // continue with your code
}

This will work for firefox, chrome, IE, etc.


Okay problem solved. Apparently all you have to do is remove the "event" parameter from onkeydown(). I think that's because IE doesn't read javascript the way Chrome does, thus it fails to work properly because there isn't a parameter passed along. =.=

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜