How to call a method inside a jquery function from

2019-05-24 14:28发布

问题:

I am looking for a way to call a method inside a jquery function.

Example : in the above code, how can I call the method() method from global scope?

(function( $ ) {

    $.fn.test = function() {

        var method = function() {
            alert('test succeeded!');
        };

    }

})( jQuery );

I tried with the following code:

$(document).ready(function() {

    $(document).test.method(); // undefined

});

But this does not help.

Fiddle: http://jsfiddle.net/kB7mc/

回答1:

Your method is of local scope available inside the function test only, you cannot access it outside the scope. Instead you can do it this way. Also while calling it, remember to put method invocation () for test i.e $(document).test().method(); instead of $(document).test.method();

(function( $ ) {

    $.fn.test = function() {
         var method = function() {
            alert('test succeeded!');
        };

         return {method:method};
    }

})( jQuery );

$(document).ready(function() {
    $(document).test().method(); // undefined
});

Fiddle

Using Jquery Plugin pattern.

(function ($) {
    var methods = {

        method : function () {
            alert('test succeeded!');
            return this; //return element for chaining
        },
         method2 : function () {
            alert('test2 succeeded!');
             return this;
        }
    };

    $.fn.test = 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 {
            $.error('Method ' + method + ' does not exist');
        }
    }

})(jQuery);

$(document).ready(function () {
    $(document).test('method'); 
    $(document).test('method2'); 

});

Fiddle