Index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!doctype html>
<html lang="en">
<head>
<meta name="Generator" content="EditPlus®" />
<meta name="Author" content="" />
<meta name="Keywords" content="" />
<meta name="Description" content="" />
<title>Document</title>
<script src="JS/jquery-1.11.1.js" type="text/javascript"></script>
<script src="JS/jquery.cookie.js" type="text/javascript"></script>
</head>
<body>
<input id="phonenum" type="text" value="18321011111" />
<input id="second" type="button" value="免费获取验证码" />
</body>
<script type="text/javascript">
function addCookie(name, value, expiresHours) {
if (expiresHours > 0) {
var date = new Date();
date.setTime(date.getTime() + expiresHours * 1000);
$.cookie(name, escape(value), { expires: date });
} else {
$.cookie(name, escape(value));
}
}
function editCookie(name, value, expiresHours) {
if (expiresHours > 0) {
var date = new Date();
date.setTime(date.getTime() + expiresHours * 1000);
$.cookie(name, escape(value), { expires: date });
} else {
$.cookie(name, escape(value));
}
}
function getCookieValue(name) {
return $.cookie(name);
}
$(function() {
$("#second").click(function() {
sendCode($("#second"));
});
v = getCookieValue("secondsremained");
if (v > 0) {
settime($("#second"));
}
});
function sendCode(obj) {
var phonenum = $("#phonenum").val();
var result = isPhoneNum();
if (result) {
addCookie("secondsremained", 60, 60);
settime(obj);
}
}
var countdown;
function settime(obj) {
countdown = getCookieValue("secondsremained");
if (countdown == 0 || countdown == undefined) {
obj.removeAttr("disabled");
obj.val("免费获取验证码");
return;
} else {
obj.attr("disabled", true);
obj.val("重新发送(" + countdown + ")");
countdown--;
editCookie("secondsremained", countdown, countdown + 1);
}
setTimeout(function() { settime(obj); }, 1000);
}
function isPhoneNum() {
var phonenum = $("#phonenum").val();
var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
if (!myreg.test(phonenum)) {
alert('请输入有效的手机号码!');
return false;
} else {
return true;
}
}
</script>
</html>
运行结果如图: