您的位置:首页 > 其它

获取手机验证码&获取普通验证码

2017-03-15 20:55 267 查看
HTML

<body>
<div class="wraper">
<h1>获取手机验证码</h1>
<input id="j_phone" class="phone" type="text">
<div id="j_getVerifyCode" class="getverify-code-btn">获取手机验证码</div>
</div>

<div class="wraper">
<h1>获取普通验证码</h1>
<div id="j_timekeeping" class="getverify-code-btn">获取验证码</div>
</div>
<script src="jquery.js"></script>
<script type="text/javascript" src="getVerifyCode.js"></script>
<script type="text/javascript">
$(function (){
//获取手机验证码
$("#j_getVerifyCode").on("click",getVerifyCode({
callBack: function (){//按钮点击后的回调函数,-----必须-----
//在这里你还是可以对你的按钮进行操作
console.log(this);
alert("验证码发送成功");
},
time: 10,//定时时间,以秒为单位,默认60秒
getCurrentTime: function (time){//获取倒计时当前时间
console.log(time);
console.log(this);//这里的这个this执行按钮
console.log("=================================");
},
isPhone: true,//是否为发送手机验证码,如果是则会验证手机号格式,-----必须-----
getPhone: function (){//获取手机号,此处一定要return
return $("#j_phone").val();
},
//phoneReg: /^1[34578]\d{9}$/,//手机号验证正则
phoneCallBack: function (){//当手机号有误时的回调,默认会中止操作
alert("您输入的手机号有误");
},
timeIsUpText: "重新发送",//倒计时时间到了后按钮所显示文字
timeRunnigText: "s后重新发送",//倒计时时间正在走的时候按钮所显示文字。默认为"xxs后重新获取"
unabledClass: "unlabed"//按钮不能用的样式,即点击按钮后的样式
}));

//获取普通验证码
$("#j_timekeeping").on("click",getVerifyCode({
callBack: function (){//按钮点击后的回调函数,-----必须-----
//在这里你还是可以对你的按钮进行操作
console.log(this);
alert("验证码发送成功");
},
time: 20,//定时时间,以秒为单位
unabledClass: "unlabed"//按钮不能用的样式,即点击按钮后的样式
}));
});
</script>
</body>


getVerifyCode.js

function getVerifyCode(options) {
return function() {
clearInterval(timer);
if(!(options && Object.prototype.toString.call(options.callBack) == "[object Function]")) {
throw new Error("必须传递参数及回调函数");
}
var that = $(this);
if(options.isPhone){
var phone = options.getPhone(),
reg = options.phoneReg || /^1[3|4|5|7|8][0-9]\d{8}$/;
if(!reg.test(phone)) {
//如果手机号码不正确,则执行手机号码对应的回调函数
options.phoneCallBack && options.phoneCallBack.call(that,phone);
return;
}
}

var timer = null,
time = options.time || 60,
unabledClass = options.unabledClass || "",
timeIsUpText = options.timeIsUpText || "重新获取",
timeRunnigText = options.timeRunnigText || " s后重新获取";
that.off("click");
4000
that.addClass(unabledClass);
timer = setInterval(function() {
//避免重复发送
if(time <= 0) {
clearInterval(timer);
/*time = 60;*/
that.html(timeIsUpText).removeClass(unabledClass);
that.on("click", getVerifyCode(options));
} else {
time--;
that.html(time + timeRunnigText);
//在外部可以获取到倒计时当前时间
if(options.getCurrentTime && (Object.prototype.toString.call(options.getCurrentTime) == "[object Function]")){
options.getCurrentTime.call(that,time);
}
}
}, 1000);
//执行回调函数
options.callBack.call(that);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: