简体   繁体   English

jQuery插件方法返回值

[英]jquery plugin method return value

I am writing a plugin for some common tasks for the drop down. 我正在为一些常见任务编写插件。 Selected Index method needs to return a value to me. 选定的索引方法需要向我返回一个值。 How can i accomplish this inside a plugin where some methods may or may not return a value? 我如何在某些方法可能会或可能不会返回值的插件内完成此操作? For methods that do not return a value, i want to maintain chainability. 对于不返回值的方法,我想保持可链接性。

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

"Unless you're returning an intrinsic value from your plugin, always have your plugin's function return the this keyword to maintain chainability." “除非您要从插件返回固有值,否则始终让插件的函数返回this关键字以保持可链接性。” - Plugins/Authoring on docs.jquery.com -docs.jquery.com上的插件/创作

This means that you return index (intrinsic value) from your selectedIndex function, like you are currently are. 这意味着您可以像当前一样从selectedIndex函数返回索引(本征值)。 Then for all other functions for which you are not currently specifying any return value, you return the this keyword to maintain chainability. 然后,对于当前未为其指定任何返回值的所有其他函数,返回this关键字以保持可链接性。 For example, to maintain chainability when calling .dropdownHelper('empty'), try the following. 例如,要在调用.dropdownHelper('empty')时保持可链接性,请尝试以下操作。

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

    return this;
},

If that doesn't work, try returning $(this) instead. 如果那不起作用,请尝试返回$(this)。

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

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