2011-06-25 68 views
2

我正在爲一些常見的下拉任務寫一個插件。選定的索引方法需要向我返回一個值。我怎樣才能完成這個插件裏面的一些方法可能會或可能不會返回一個值?對於不返回值的方法,我想維護可鏈接性。jquery插件方法返回值

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'); 
}); 
}; 

回答

1

「除非你返回從你的插件的內在價值,總是有你的插件的功能返回this關鍵字來維持chainability。」 - Plugins/Authoring on docs.jquery.com

這意味着你從你的selectedIndex函數返回索引(內在值),就像你現在一樣。然後,對於您當前未指定任何返回值的所有其他函數,您將返回此關鍵字以維護可鏈接性。例如,爲了在調用.dropdownHelper('空')時保持可鏈接性,請嘗試以下操作。

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

    return this; 
}, 

如果這不起作用,請嘗試返回$(this)來代替。