【问题标题】:How to add a callback to ths function?如何向 ths 函数添加回调?
【发布时间】:2013-04-23 15:05:32
【问题描述】:

你好我found this snippet模拟打字机效果:

$.fn.teletype = function(opts){
    var $this = this,
        defaults = {
            animDelay: 50
        },
        settings = $.extend(defaults, opts);

    $.each(settings.text.split(''), function(i, letter){
        setTimeout(function(){
            $this.html($this.html() + letter);
        }, settings.animDelay * i);
    });
};

Wich 似乎工作得很好,但我需要知道函数何时完成,我尝试添加另一个参数并在其末尾运行它:

$.fn.teletype = function(opts,callback){
    var $this = this,
        defaults = {
            animDelay: 50
        },
        settings = $.extend(defaults, opts);

    $.each(settings.text.split(''), function(i, letter){
        setTimeout(function(){
            $this.html($this.html() + letter);
        }, settings.animDelay * i
        callback();
    });
};

但它在进程完成之前执行

我如何知道该回调函数的放置位置?

【问题讨论】:

  • 您不能将它按原样粘贴到您的代码中,您必须检测所有 setTimeouts 何时完成。

标签: jquery jquery-plugins callback


【解决方案1】:

each中的最后一个元素调用它,这将在动画应用到每个字母后调用回调

$.fn.teletype = function(opts,callback){
    var $this = this,
        defaults = {
            animDelay: 50
        },
        settings = $.extend(defaults, opts);


    $.each(settings.text.split(''), function(i, letter){
        setTimeout(function(){
            $this.html($this.html() + letter);
            if(i === (settings.text.length -1)) {
                callback();
            }
        }, settings.animDelay * i
    });

};

【讨论】:

  • 这仍然会很快发生。
  • 显然您的编辑实际上并没有算作编辑,所以我无法撤消投票。
  • 奇怪...也许是因为我没有在编辑中包含评论?还是谢谢
  • 尝试修复原始代码中的错字,setTimeout 缺少)
【解决方案2】:

检查setTimeout回调中的条件:

$.each(settings.text.split(''), function(i, letter){
    setTimeout(function(i){
        $this.html($this.html() + letter);
        if(i == (settings.text.length -1)){

          callback()

        }
    }, settings.animDelay * i

});

【讨论】:

  • 这将调用 callback() 两次
  • @cfs,抱歉,忘记从 OP 问题中删除第二个 callback()
猜你喜欢
  • 1970-01-01
  • 2015-08-27
  • 2015-10-22
  • 2018-02-24
  • 2023-03-07
  • 1970-01-01
  • 2013-12-18
  • 2012-04-05
  • 2018-07-20
相关资源
最近更新 更多