【问题标题】:jquery plugin method return valuejquery插件方法返回值
【发布时间】:2011-06-25 07:04:38
【问题描述】:

我正在为下拉菜单的一些常见任务编写插件。 Selected Index 方法需要返回一个值给我。我如何在插件中完成此操作,其中某些方法可能会或可能不会返回值?对于不返回值的方法,我想保持可链接性。

jQuery.fn.dropdownHelper = function(method) {
var methods = {
    init: function(){ },
    empty: function(){
        if (this.tagName == 'SELECT')
            this.options.length = 0;
    },
    selectedIndex: function(){
        var index = this.selectedIndex; 
        if(index == 'undefined')
            index = -1;
        alert (index);
        return index;   
    }
};
return this.each(function() {    
    // Method calling logic
    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 );
    else
        $.error( 'Method ' +  method + ' does not exist' );
});
};

【问题讨论】:

    标签: jquery plugins methods


    【解决方案1】:

    “除非你从插件返回一个内在价值,否则总是让你的插件函数返回 this 关键字以保持可链接性。” -Plugins/Authoring on docs.jquery.com

    这意味着你从你的 selectedIndex 函数返回索引(内在值),就像你现在一样。然后对于您当前未指定任何返回值的所有其他函数,您返回 this 关键字以保持可链接性。例如,要在调用 .dropdownHelper('empty') 时保持可链接性,请尝试以下操作。

    empty: function(){
        if (this.tagName == 'SELECT')
            this.options.length = 0;
    
        return this;
    },
    

    如果这不起作用,请尝试返回 $(this)。

    【讨论】:

      猜你喜欢
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      • 2014-03-16
      • 1970-01-01
      相关资源
      最近更新 更多