本文摘自PHP中文网,作者青灯夜游,侵删。
判断方法:1、使用“$.isNumeric(x)”,可判断指定参数“x”是否是数字值;2、使用“isNaN(x)”,可判断参数“x”是否是为数字值;3、使用正则表达式“/^(-)?\d+(\.\d+)?$/”配合test来判断数字。
本教程操作环境:windows7系统、jquery3.2.1版,该方法适用于所有品牌电脑。
相关推荐:《jQuery视频》
jquery判断变量是否为数字的方法
方法1、使用$.isNumeric()
jquery里内置的一个用来判断是否为数字的函数$.isNumeric()。$.isNumeric() 函数用于判断指定参数是否是一个数字值。
用$.isNumeric()来判断是否为数字的话,一些特殊的字符会被当成8进制或12进制的数字,判定为true。
注意:在jQuery 3.0中,$.isNumeric()方法只有接收number类型的参数,或者是可以被强制为有限数值的 string类型的参数时,才会返回true,否则返回false。
语法
参数:
value:任意类型,需要进行判断的任意值。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 | $.isNumeric(3.13);
$.isNumeric( "3.13" );
$.isNumeric(-3.13);
$.isNumeric( "-3.13" );
$.isNumeric( "03.13" );
$.isNumeric(01);
$.isNumeric(001);
$.isNumeric(+3.13);
$.isNumeric(0xFF);
$.isNumeric( "0xFF" );
$.isNumeric(true);
$.isNumeric(NaN);
|
方法2:使用isNaN() 函数
1 2 3 4 5 6 7 8 | var val = $( "#test" ).val();
var ival = parseInt(val);
alert( typeof (ival));
if (!isNaN(ival)){
alert(val + "是数字" );
} else {
alert(val + "不是数字" );
}
|
说明: isNaN()函数,如果传入的参数是数字返回false,否则返回true
方法3:使用正则表达式判断
常用正则:
1 2 3 4 5 6 7 8 9 10 | " /^(0|[1-9]\d*)$/"
"^[0-9]*[1-9][0-9]*$"
"^((-\\d+)|(0+))$"
"^-[0-9]*[1-9][0-9]*$"
"^-?\\d+$"
"^\\d+("
"^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$"
"^((-\\d+("
"^(-(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*)))$"
"^(-?\\d+)("
|
实例:
1 2 | var r = /^\+?[1-9][0-9]*$/;
r.test(str);
|
或者:
1 2 3 4 5 6 7 8 | function isNumber(value) {
var patrn = /^(-)?\d+(\.\d+)?$/;
if (patrn.exec(value) == null || value == "" ) {
return false
} else {
return true
}
}
|
知识拓展:JavaScript的Number()函数 ―-这里不是判断方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <script type= "text/javascript" >
var test1= new Boolean( true );
var test2= new Boolean( false );
var test3= new Date();
var test4= new String( "999" );
var test5= new String( "999 888" );
document.write(Number(test1)+ "<br />" );
document.write(Number(test2)+ "<br />" );
document.write(Number(test3)+ "<br />" );
document.write(Number(test4)+ "<br />" );
document.write(Number(test5)+ "<br />" );
</script>
|
输出的结果是:
1 2 3 4 5 | 1
0
1492855437972
999
NaN
|
可以看出在JavaScript中0代表false,1代表true。但是我测试了一下,除0以外的数放在if的条件中,都可以执行if语句内容。所以。可以得出除0以外的所有数都可以代表true。
更多编程相关知识,请访问:编程课程!!
以上就是jquery如何判断是否为数字?的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
jQuery如何判断radio是否选中
jQuery三大版本之间有什么区别?
jQuery收费吗?
jQuery怎么让select不可选
jQuery如何判断是否有子元素
jQuery 轮播图怎么写
jQuery怎么比较两个数字大小
基于jQuery和html5的日历时钟插件 的图文详解
jQuery 如何判断 是否相等
jQuery如何设置不可点击
更多相关阅读请进入《jQuery》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » jquery如何判断是否为数字?