jQuery - 在插件中添加回调前后

标签 jquery jquery-plugins jquery-callback

我想在我的自定义 jQuery 插件中添加 after 和 before 回调。 我以前从未尝试过回调。所以请帮助我。

这是我的插件代码


(function($){
    $.fn.OneByOne = function( options ){

        var defaults = {
            startDelay:5,           
            duration: 1000,
            nextDelay: 700
        };

        var options = $.extend(defaults, options);
        var delay = options.startDelay;
        return this.each(function(){

            var o = options;
            var obj = $(this);                
            var a = $('a', obj);        

            obj.css({'margin-top':'100px','opacity': '0'});         
            obj.delay(delay).fadeIn().animate({opacity: 1,'margin-top':'0'}, o.duration);
            delay += o.nextDelay;


        });


    };
})(jQuery);

回调前后调用的位置


我想在回调之前调用before:

    obj.css({'margin-top':'100px','opacity': '0'});         
    obj.delay(delay).fadeIn().animate({opacity: 1,'margin-top':'0'}, o.duration);
    delay += o.nextDelay;

并希望在上述代码之后调用 after 回调。

我需要回调什么


我想使用

http://ricostacruz.com/jquery.transit/

回调中的转换。

请告诉我如何在调用插件时使用回调。

谢谢。

最佳答案

  1. 让用户在回调之前和之后传递。 在默认值中,指定默认回调函数:

    var defaults = {
        startDelay:5,           
        duration: 1000,
        nextDelay: 700 
    };
    
    // Test if user passed valid functions
    options.before = typeof options.before == 'function' ? options.before || function(){};
    options.after = typeof options.after == 'function' ? options.after || function(){};
    

    $ 插件中的选项以哈希形式传递,因此用户会将它们作为

    $("…").OneByOne({…, before: function() {}, after: function() {});
    
  2. 在您的插件代码中,您必须 Hook 它们以便调用它们(默认的,或任何用户定义的回调):

    // Before is simply called before starting animation
    // Use call or apply on the callback passing any wanted argument.
    before.call(this, obj);
    // After callback is passed directly to animate function and gets called on animation complete.
    obj.delay(delay).fadeIn().animate({opacity: 1,'margin-top':'0'}, o.duration, after);
    
  3. “before”回调的任何参数都可以在用户定义的回调之前使用; after 回调将使用 obj 上下文调用,因此在回调后定义的任何用户内,$(this) 你的 obj。

关于jQuery - 在插件中添加回调前后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16520922/

相关文章:

c# - 带有 jQ​​uery DatePicker 的 ASP.NET

javascript - Jquery条件不起作用

javascript - 如何检查表单是否至少填写了一个字段

javascript - 如何以及在何处初始化 Backbone View 中的 jquery 数据表

jquery - 如何取消 AjaxForm 上的提交

jquery - 设置 JQuery event.preventDefault() 时绕过 window.open 上的弹出窗口阻止程序

jQuery $.animate() 多个元素但只触发一次回调

javascript - 从 XML 文件中分离出一个结果

jquery - 当行具有或不具有 colspan 时,表中的排序不起作用

jquery - 全日历重新获取事件回调