简体   繁体   中英

jQuery plugin method that doesn't take an element

I'm authoring a jQuery plugin in which one of the methods that I'd like to write will not take a selector argument and does not need to pass an element. I'd like it to be available by a call like $.myMethod() like the built in $.ajax() method. Up to now I've tried something like

$.fn.myMethod(options) {
     console.log("I've been called");
}

This works when I try $('.a_selector').myMethod() but not when I try $.myMethod() .

Is this doable with a jQuery plugin or is it only available for interal functions.

The purpose of this method is to perform an action on some data that is stored in jQuery.data. I recognize that they jQuery.data is associated with an element, but in this case I've hard coded it to the body element to make things easier for the end user.

The functions that are members of $.fn apply to jQuery objects, not to the $ object itself. If you want to create such a method, you only have to write:

$.yourMethod = function() {
    // Do something.
};

Now you can call it without a jQuery object:

$.yourMethod();

An elaborate way of declaring such a function can be

$.extend({myMethodA:function(){
                            //Do something
                            },
          myMethodB:function(){
                        //Do something else
                                }       
                 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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