在项目中,我们可能会碰到一些禁用某些标签的事,比如说禁用button按钮的点击事件。对于button按钮,只需要让它的disabled属性等于diabled或true,那这个按钮就不会再触发点击事件了。但是,如果这个按钮是一个a标签,那disabled属性不再对a标签起作用,因为a标签中没有这个属性。
我当时在项目中碰到这个问题时,着时纠结了半天。后来想到,既然要让这个a标签做成的按钮不能点击,那我先把它的click事件给解绑了,然后在需要的时候重新绑定不就可以了吗?想到就做,果然成功了。
以下是代码,需求是成功发送短信验证码后,60秒后才可再次点击重新发送。
$(function(){
var phoneBox = $('#phone');//手机号码输入框
var phoneTipBox = $('#phone_tip');//手机号码提示
var getCodeBtn = $('#get_code');//获取验证码按钮
var phoneCodeBox = $('#phone_code');//手机验证码输入框
//获取短信验证码的方法
var sendPhoneCode = function(){
if (isPhoneCorrect){ //isPhoneCorrect表示输入的手机号码格式是否正确
var phone = phoneBox.val();
$.ajax({
url : "/user/passport/register_send_code",
type : "post",
data : { phoneNo : phone},
success : function(rdata){
if (rdata.errCode == 0){
phoneTipBox.removeClass().addClass("onCorrect").html(rdata.errDesc);
//获取验证码成功后开始进行禁用倒计时
reSendCountdown();
}else if (rdata.errCode == -1){
phoneTipBox.removeClass().addClass("onError").html(rdata.errDesc);
}else {
alert(rdata.errDesc);
}
}
});
}else {
phoneTipBox.removeClass().addClass("onError").html("手机号码输入错误!");
isPhoneCorrect = false;
}
}
//60s后重新发送手机验证码
var reSendCountdown = function(){
var count = 60;//禁用时间为60秒
//解绑按钮的点击事件(该按钮是一个a标签)
getCodeBtn.html(count+"秒后点击重新发送").addClass("resend").unbind("click");
var resend = setInterval(function(){
count--;
if (count > 0){
getCodeBtn.html(count+"秒后点击重新发送");
}else {
clearInterval(resend);//清除计时
//重新绑定按钮的click事件
getCodeBtn.bind("click", sendPhoneCode).removeClass("resend").html("重新获取验证码");
phoneTipBox.removeClass().addClass("tishi").html("如果没有收到短信,请点击重新发送!");
}
}, 1000);
}
//点击按钮触发获取短信验证码事件
getCodeBtn.click(sendPhoneCode);
});