【问题标题】:jquery plugin: how to return default value when some options are not set?jquery插件:未设置某些选项时如何返回默认值?
【发布时间】:2013-07-13 21:50:23
【问题描述】:

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

(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

【问题讨论】:

    标签: jquery jquery-plugins extend jquery-1.9


    【解决方案1】:

    我使用这些代码来定义默认值和选项并且它有效:

    var defaults = {
        speed : 150 ,
        check_effect: "fade" ,
        uncheck_effect: "fade" ,
        };
    
    var options = $.extend({}, defaults, options);
    

    而且我不使用函数来定义你所拥有的默认值!

    【讨论】:

    • 但您必须在 $.fn.plugin 中使用第 9-21 行(在之前的小提琴中),如下所示:jsfiddle.net/BWZWG/7
    • 感谢您的帮助。但这不是我需要的,因为这样我不能将任何选项传递给init 和其他方法。看看我的测试 - jsfiddle.net/BWZWG/8
    • 为什么不把方法带入 $.fn.plugin?看看jsfiddle.net/BWZWG/10
    • 行得通!我从来不知道我们能做到这一点。我遵循 jquery 网站的格式/结构。
    • 我们应该将此bug 告知 jquery 以防误导! :)
    【解决方案2】:

    我认为答案是,

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-23
      • 2012-04-05
      • 2016-11-03
      • 1970-01-01
      • 2015-09-27
      • 2023-03-18
      • 2020-06-14
      • 2021-12-21
      相关资源
      最近更新 更多