我编写了一个 jQuery 插件,它在 div 中输入一个数字,然后将其计数。我试图添加一个回调,所以当它完成时,它会从下一个 div 开始。
当它开始处理下一个 div 时,它首先重置当前 div 中的数字,然后按预期继续下一个 div。我怀疑它与在插件内部使用“this”有关。
我该如何防止这种情况发生?谢谢
我的插件:
(function( $ ) {
$.fn.countUp = function(options) {
var settings = $.extend( {
'startFrom' : 0,
'countTo' : Number(this.text()),
'start' : 10,
'frequency' : 200,
'jump' : 1,
'target' : this,
'log' : false,
'callback' : ''
}, options);
var intRegex = /^\d+$/;
if(intRegex.test(settings.countTo) && intRegex.test(settings.startFrom) ) {
// Both settings are integers, get started:
if(settings.startFrom<settings.countTo){
offset = settings.jump;
}else{
offset = -1 * settings.jump;
}
current_number = settings.startFrom;
settings.target.html(current_number);
checkNumber();
var timer;
function checkNumber(){
if(offset<0){
if(current_number <= settings.countTo)
{
current_number = settings.counTo;
clearTimeout(timer);
if (typeof settings.callback == 'function') { // make sure the callback is a function
settings.callback.call(this); // brings the scope to the callback
}
}
else
{
current_number += offset;
timer=setTimeout(function(){checkNumber()},settings.frequency);
}
}else{
if(current_number >= settings.countTo)
{
current_number = settings.counTo;
clearTimeout(timer);
if (typeof settings.callback == 'function') { // make sure the callback is a function
settings.callback.call(this); // brings the scope to the callback
}
}
else
{
current_number += offset;
timer=setTimeout(function(){checkNumber()},settings.frequency);
}
}
settings.target.html(current_number);
if(settings.log){console.log(settings.target.attr('id'))};
}
}else{
if(settings.log){console.log('From countUp: Please use an integer for startFrom and countTo arguments.');}
}
};
})( jQuery );
这就是我所说的:
$(document).ready(function(){
$("#output").countUp({
'log' : true,
'callback' : call2
});
function call2(){
$("#output2").countUp({
'log' : true,
'callback' : call3
});
}
function call3(){
$("#output3").countUp({'log' : true});
}
})