用jquery / javascript检测数字或字母? [英] Detect numbers or letters with jquery/javascript?

查看:51
本文介绍了用jquery / javascript检测数字或字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用if语句仅在用户输入字母或数字时才运行代码。

I want to use an if-statement to run code only if the user types in a letter or a number.

我可以使用

 if(event.keyCode == 48 || event.keyCode == 49 || event.keyCode == 50..) {
       // run code
 }

有更简单的方法吗?也许某些密钥代码在所有网络浏览器中都不起作用?

Is there an easier way to do this? Maybe some keycodes don't work in all web browsers?

推荐答案

如果你想检查一系列字母,你可以使用更多低于和低于:

If you want to check a range of letters you can use greater than and less than:

if (event.keyCode >= 48 && event.keyCode <= 57)
    alert("input was 0-9");
if (event.keyCode >= 65 && event.keyCode <= 90)
    alert("input was a-z");

要进行更动态的检查,请使用正则表达式:

For a more dynamic check, use a regular expression:

var inp = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9-_ ]/.test(inp))
    alert("input was a letter, number, hyphen, underscore or space");

参见 keyCode 属性的event.keyCoderel =noreferrer> MDC文档,解释了它与之间的区别属性及其适用的事件。

See the MDC documentation for the keyCode property, which explains the difference between that and the which property and which events they apply to.

这篇关于用jquery / javascript检测数字或字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆