在网页上,模拟实现银行客户端的功能:四字隔开且只能输入数字,有两种方法,测试兼容主流PC端浏览器;手机上,有些厂商会出现随机加入一些字符
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>模拟实现四字隔开</title>
</head>
<body>
<input type="text" id="cardno" onkeyup="separate(this)"/>
<input type="text" id="cardno1" onkeyup="separate1(this)" />
<script>
function separate(O){
var val =O.value.trim().replace(/\s/g,'');
var word = val.split('')[val.length-1];
if(isNaN(word)){
val=val.substring(0,val.length-1);
}
var val2='';
for(var i=0;i<val.length;i++){
val2+=val.split('')[i];
if((i+1)%4==0){
val2+=' ';
}
}
O.value = val2;
}
function separate1(O){
O.value = O.value.replace(/\D/g, "").replace(/....(?!$)/g, "$& ");
}
</script>
</body>
</html>