jquery插件:如何在未设置某些选项时返回默认值?

时间:2013-07-13 21:50:23

标签: jquery jquery-plugins extend jquery-1.9

我无法弄清楚我在这个插件中做错了什么,

(function($){

    var methods = {

        defaults: function(options) {

            // Default options.
            var defaults = {
                setup: {
                    tester1: "hello1",
                    tester2: "hello2",
                    tester3: "hello3"
                },
                tester: "hello world"               
            }

            // Always leave this line here.
            var options = $.extend(defaults, options);
            alert(options.setup.tester2);

            // Return the processed options.
            return options;

        },

        init : function( options ) {

            var $this = this;
            var o = $this.plugin('defaults',options);

        },

        something : function( options ) {


        }
    };

    $.fn.plugin = function( method ) {

        // @reference: http://docs.jquery.com/Plugins/Authoring#Namespacing
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );  // always change 'init' to something else if you different method name.
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.plugin' );
        }

        return this; 

    };

})(jQuery);

所以,

jQuery().plugin(); // return 'hello2' --> correct

但是,

jQuery().plugin({setup:{tester1:"x"}}); // return 'undefined' --> should be 'hello2'

任何想法我应该做什么或者我错过了什么?

jsfiddle

2 个答案:

答案 0 :(得分:1)

我使用此代码来定义默认值和选项,它可以工作:

var defaults = {
    speed : 150 ,
    check_effect: "fade" ,
    uncheck_effect: "fade" ,
    };

var options = $.extend({}, defaults, options);

我没有使用函数来定义默认值,就像你拥有的那样!

答案 1 :(得分:0)

我认为答案是,

var options = $.extend( true, {}, defaults, options );