search

Home  >  Q&A  >  body text

javascript - How come the key value of a js key minus a number becomes NaN

This is the code and browser screenshot. The first one is number, the second one is also number, but the third one is NaN.
I want to get a key combination, such as Alt 1...Alt 9 and then decrease the key value. Go to a number that corresponds to the value of the option of select
but it keeps reporting NaN

$(function(){
    $(document).keydown(function(event){
        if(event.keyCode <=57 && event.keyCode >= 49 && event.altKey){
            var selectval = (event.keyCode - 48);
            console.log(typeof(event.keyCode));
            console.log(typeof(selectval));
            console.log(selectval);
        }
    });
})

为情所困为情所困2775 days ago701

reply all(6)I'll reply

  • PHP中文网

    PHP中文网2017-05-19 10:32:37

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-19 10:32:37

    var selectval = (event.KeyCode - 48); => var selectval = (event.keyCode - 48);
    
    是KeyCode还是keyCode?

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-19 10:32:37

    There’s nothing wrong with writing it in native language

    document.addEventListener('keydown',function(event){
        if(event.keyCode <=57 && event.keyCode >= 49 && event.altKey){
                var selectval = (event.keyCode - 48);
                console.log(typeof(event.keyCode));
                console.log(typeof(selectval));
                console.log(selectval);
            }
    },false);

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-19 10:32:37

    Use event.ctrlKey, event.shiftKey, event.altKey to determine whether the ctrl key, shift key and alt key are pressed

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-19 10:32:37

    After changing several environments, this situation finally occurred. They are all the highest version of Google. I don’t know how there are several computers without undefined

    The keyCode received by the new variable is undefined;
    As for why I don’t understand it yet, can someone please explain the mechanism

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-19 10:32:37

    jQuery will help you with compatibility processing, please use event.which代替event.keyCode.

    No need for jQuery:

    // 获取用户单击键盘的“键值”
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

    reply
    0
  • Cancelreply