hdjs
Version:
hdjs framework
77 lines (76 loc) • 2.7 kB
JavaScript
define([
'dist/static/component/message',
'jquery'
], function (Message,$) {
return function (option) {
option = $.extend({
//后台发送地址
url: '',
//发送间隔时间
timeout: 60,
//发送前执行的动作
before: function () {
return true;
}
}, option);
//上次发送的时间
var obj = {
//按钮
el: $(option.el),
//定时器编号
intervalId: 0,
//初始化
init: function () {
var This = this;
this.el.on('click', function () {
This.send();
})
this.update();
},
//更改状态
update: function () {
var This = this;
This.intervalId = setInterval(function () {
if (This.getWaitTime() > option.timeout) {
clearInterval(This.intervalId);
This.el.removeAttr('disabled').text('发送验证码');
} else {
var diff = option.timeout - This.getWaitTime();
This.el.text(diff + "秒后再发送").attr('disabled', 'disabled');
}
}, 100);
},
//发送验证码
send: function () {
var This = this;
var username = $.trim($(option.input).val());
//验证手机号或邮箱
if (!/^\d{11}$/.test(username) && !/^.+@.+$/.test(username)) {
Message('帐号格式错误', '', 'info');
return;
}
if (option.before() === true) {
This.setSendTime();
$.post(option.url, {username: username}, function (response) {
Message(response.message);
if (response.valid == 1) {
This.setSendTime();
This.update();
}
}, 'json');
}
},
//获取发送间隔时间
getWaitTime: function () {
var time = localStorage.getItem('validCodeSendTime');
var diff = $.now() * 1 - (time * 1);
return Math.floor(diff / 1000)
},
//设置间隔时间
setSendTime: function () {
localStorage.setItem('validCodeSendTime', $.now());
}
}
obj.init();
}
})