jQuery插件调用嵌套函数

时间:2013-03-03 03:52:09

标签: jquery jquery-plugins

是否可以调用嵌套函数并使用$(this)而不必将$(this)作为参数传递?例如:$(this).setValidators()而不是methods.setValidators($(this))

(function($){
    var methods = {
        init: function(options){
            var _this = this;
            var inputs = $(":input)", _this);

            inputs.each(function(){
               methods.setValidators($(this));

               //would it be possible to do the following somehow?
               //$(this).setValidators();
            });
        },

        setValidators: function(obj){
            obj.on('click', anotherFunction);
        },

        /*
        setValidators: function(){
            $(this).on('click', anotherFunction);
        }
        */

        anotherFunction: function(){
            //do stuff
        }
    }

    $.fn.myPlugin = function(method){
        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{
            return(false);
        }
    };
})(jQuery);


$('form').myPlugin();

0 个答案:

没有答案