js代码如下:
(function() {
$.fn.countDown = function(userOptions) {
var defaultOptions = {
duration: 60
},
opt = $.extend({}, defaultOptions, userOptions),
time = opt.duration,
clickFlag = true;
function cd() {
if(time > 0) {
$(this).text('剩余' + time + '秒').css('cursor', 'not-allowed');
setTimeout(cd, 1000);
time--;
clickFlag = false;
} else if(time == 0) {
$(this).text('重新发送验证码').css('cursor','pointer');
time = opt.duration;
clickFlag = true;
}
}
$(this).on({
click: function() {
if(clickFlag == true) {
cd.call(this);
} else if(clickFlag == false) {
alert('不能重复点击!');
}
}
});
};
}());
$(document).ready(function() {
$('#CD_time').countDown({
duration: 120
});
});
经过几个前辈的指点,先修改代码如下:(已能顺利执行)
(function() {
$.fn.countDown = function(userOptions) {
var defaultOptions = {
duration: 60
},
opt = $.extend({}, defaultOptions, userOptions),
time = opt.duration,
clickFlag = true,
_this = this;
function cd() {
if(time > 0) {
$(_this).text('剩余' + time + '秒').css('cursor', 'not-allowed');
setTimeout(cd, 1000);
time--;
clickFlag = false;
} else if(time == 0) {
$(_this).text('重新发送验证码').css('cursor', 'pointer');
time = opt.duration;
clickFlag = true;
}
}
$(this).on({
click: function() {
if (clickFlag == true) {
cd.call(this);
} else if (clickFlag == false) {
alert('不能重复点击!');
}
}
});
};
}());
$(document).ready(function() {
$('#CD_time').countDown({
duration: 120
});
});
因为你调用cd函数时,只有第一次绑定了this,从第二次开始就cd里面的this都变成了window。
你在函数cd的第一行加一句:
console.log(this)
打印一下this看看就明白了。修改方法:
在函数cd外加一句:
var _this = this;
,然后把函数cd里面的this都改成_this即可。