fgm实例练习笔记-3.6判断数字是否为两位数

来源:互联网 发布:堆和栈的区别java 编辑:程序博客网 时间:2024/05/20 16:34
<script>window.onload = function(){    var otex = document.getElementsByTagName("input");    otex[0].onkeyup = function(){    this.value = this.value.replace(/[^\d]/,"");}//输入时直接删除掉不符合数字的内容    otex[1].onclick = function(){    otex[0].value.length == 2 ? alert ("Right,这是2位数")://.length得到字符串长度,是两位数就报正确,不是就报位数    alert ("这是" + otex[0].value.length + "位数");}    };</script>

原版引入了test()方法,检测字符串是否匹配正则表达式:RegExpObject.test(string),正则表达式 /^\d{2}$/,检测otex[0].value匹配数字是否匹配了两次。注意圆括号的使用 (),结尾不要忘了 )。
并加入了没有输入内容时的警告。

(otex[0].value == "") ? alert("please") : alert(/^\d{2}$/.test(parseInt(otex[0].value)) ? "right,这是2位数" : "这是“ + otex[0].value.length +"位数";)
原创粉丝点击