练习地址:http://www.fgm.cc/learn/lesson3/06.html
先贴我的代码:
HTML:
<html lang="zh">
<head>
<meta charset="utf-8">
<title>判断数字是否为两位数title>
<link rel="stylesheet" type="text/css" href="6_isTwoNumber.css">
head>
<body>
<input type="text">
<button>是否为两位数button>
<script type="text/javascript" src="6_isTwoNumber.js">script>
body>
html>
CSS:
input {
width: 50px;
margin-left: 600px;
}
JavaScript:
window.onload = function() {
var input = document.getElementsByTagName("input")[0];
var isTwo = document.getElementsByTagName("button")[0];
input.onkeyup = function() {
this.value = this.value.replace(/[^\d]/,"");
}
isTwo.onclick = function() {
if(input.value == ""){
alert("请输入数字");
}else{
var num = input.value.split("");
if(num.length == 2){
alert("√是两位数");
}else{
alert("这是"+num.length+"位数");
}
}
}
}
再来看大佬的代码:简洁大气。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>判断数字是否为两位数title>
<style>
body{font:12px/1.5 arial;text-align:center;}
.f-text{width:50px;border:1px solid #ccc;background:#f0f0f0;font-family:inherit;padding:3px;margin-right:10px;}
style>
<script type="text/javascript">
window.onload = function ()
{
var aInput = document.getElementsByTagName("input");
var aSpan = document.getElementsByTagName("span")[0];
var i = 0;
//这里我是不会写的,借鉴了大佬的onkeyup
aInput[0].onkeyup = function ()
{
this.value = this.value.replace(/[^\d]/,"")
}
aInput[1].onclick = function ()
{ //这里我也没有注意到,要考虑用户输入
(aInput[0].value == "") ?
alert("请输入数字!") :
//这个条件运算符的运用真的想不到我脑子里面去。。特别是正则表达式
alert(/^\d{2}$/.test(parseInt(aInput[0].value)) ? "√ 是两位数" : "这是" + aInput[0].value.length + "位数");
}
};
script>
head>
<body>
<input type="text" class="f-text" /><input type="button" value="是否为两位数" />
body>
html>