creating a jquery plugin with multiple functions

后端 未结 2 1582
鱼传尺愫
鱼传尺愫 2020-12-15 11:51

ok am kinda new to plugins i have used many in my projects, i have also written basic plugins that just work on elements with options:

(function($){
    $.fn         


        
2条回答
  •  情话喂你
    2020-12-15 12:32

    Following Samuel's answer, you can also use the following to avoid double handling the function names:

    (function($) {
        $.fn.myplugin = function(options, param) {
            if( typeof(this[options]) === 'function' ) {
                this[options](param);
            }
            // do default action
    
            this.function1 = function() {
                //do something
            }
    
            this.function2 = function(param) {
                //do something else (with a parameter)
            }
        }    
    }
    

    The addition of the param variable allows you to call functions like below:

    $.myplugin(); // does default behaviour
    $.myplugin('function1'); // run function 1
    $.myplugin('function2'); // run function 2
    $.myplugin('function2',{ option1 : 4, option2 : 6 }); // run function 2 with a parameter object
    

    See http://jsfiddle.net/tonytlwu/ke41mccd/ for a demo.

提交回复
热议问题