使用 javascript onkeydown 处理密钥

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7555136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:31:22  来源:igfitidea点击:

Handle key using javascript onkeydown

javascripthtmlregexonkeydown

提问by Rad

I have this code

我有这个代码

function verifyKey(e)
{
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (e)
        keycode = e.which;
    regex=/[1-9]/;
    if(regex.test(keycode))
        return true;
    else
        void(0);
}

in the html I added an input and I add the onkeydown event onkeydown="verifyKey(event);"

在 html 中,我添加了一个输入,并添加了 onkeydown 事件 onkeydown="verifyKey(event);"

I like to verify the key before it display on the text

我喜欢在它显示在文本上之前验证密钥

If the key is a number or coma(,) or full stop(.) then accept the key else refuse it

如果键是数字或 coma(,) 或句号 (.) 则接受键否则拒绝它

Thanks

谢谢

回答by AmGates

Here in your code you are testing the regular expression defined with the keycode, so every chearactes on the keyboard will be allowed since the keycode of every key is numbers, so you will not get the result what you expect. Instead of using the regular expression try the below code

在您的代码中,您正在测试使用键码定义的正则表达式,因此键盘上的每个字符都将被允许,因为每个键的键码都是数字,因此您不会得到预期的结果。而不是使用正则表达式尝试下面的代码

<html>
<head>
<script type="text/javascript">
function verifyKey(e)
{
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (e)
        keycode = e.which;


    if((keycode>=48 && keycode<=57))
    {alert("if")
        return true;
    }
    else if((keycode == 188)||(keycode == 190))
    {alert("elseif");
        return true;
    }
    else
    {alert("else")
        return false;
    }
}


</script>
</head>
<body>
<input type="text" onkeypress="return verifyKey(event)" />
</body>
</html>