繁体   English   中英

jQuery-如果没有options参数,则回调失败

[英]jQuery - Callback failing if there is no options parameter

我正在尝试构建一个像这样的简单插件

(function($) {

        $.fn.gpSlideOut = function(options, callback) {

            // default options - these are used when no others are specified
            $.fn.gpSlideOut.defaults = {
            fadeToColour: "#ffffb3",
            fadeToColourSpeed: 500,
            slideUpSpeed: 400
            };

        // build main options before element iteration
            var o = $.extend({}, $.fn.gpSlideOut.defaults, options);

             this.each(function() {
                $(this)
                .animate({backgroundColor: o.fadeToColour},o.fadeToColourSpeed)
                .slideUp(o.SlideUpSpeed, function(){
                    if (typeof callback == 'function') {  // make sure the callback is a function
                        callback.call(this);  // brings the scope to the callback
                    }
                });

                });

            return this;

        };

        //  invoke the function we just created passing it the jQuery object
    })(jQuery);

我一直感到困惑的是,通常在jQuery插件上,您可以这样调用:

$(this_moveable_item).gpSlideOut(function() {
                // Do stuff
            });

没有options参数,但是如果我这样做,它将错过回调,所以我必须始终

var options = {}
$(this_moveable_item).gpSlideOut(options, function() {
                    // Do stuff
                }); 

即使我只想使用默认值。

无论如何,无论是否有options参数,都要确保调用了回调函数?

干杯。

//you have no second parameter
if (callback == undefined)
   ...

//have a function
if ($.isFunction(options))
  ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM