1

This bit of code generates that error in Chrome's JavaScript console & I'm not sure why. After Googling around for people with similar issues, I haven't found any D:

The error message suggests that the issue is with the event.which() but I don't see how I'm using it any differently from expected, other people with similar don't seem to have had problem with it.

$(document).keypress(function(event) {
    switch (event.which()) {            
        case 38 :   keyNorthPressed = true;
                    break;
        case 39 :   keyEastPressed = true;
                    break;
        case 40 :   keySouthPressed = true;
                    break;
        case 41 :   keyWestPressed = true;
                    break;
    }
});

Thanks in advance.


The answer here.

There are two possible ways two retrieve the event key code:

event.keyCode or event.which

Your code should be:

$(document).keypress(function(event) {
    var code = event.keyCode || event.which;
    switch(code) {       
        case 38 :   keyNorthPressed = true;
                    break;
        case 39 :   keyEastPressed = true;
                    break;
        case 40 :   keySouthPressed = true;
                    break;
        case 41 :   keyWestPressed = true;
                    break;
    }
});

event.keyCode and event.which are attributes, not methods, you can't call them with a ().

4

1 回答 1

1

答案在这里

两种检索事件键码的可能方式:

event.keyCode or event.which

您的代码应该是:

$(document).keypress(function(event) {
    var code = event.keyCode || event.which;
    switch(code) {       
        case 38 :   keyNorthPressed = true;
                    break;
        case 39 :   keyEastPressed = true;
                    break;
        case 40 :   keySouthPressed = true;
                    break;
        case 41 :   keyWestPressed = true;
                    break;
    }
});

event.keyCode 和 event.which 是属性,不是方法,不能用 () 调用。

于 2013-02-23T13:22:12.773 回答