creating a jquery plugin with multiple functions

后端 未结 2 1577
鱼传尺愫
鱼传尺愫 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:47

    If you look at the design of some of the other jQuery plugins and jQuery UI, what they do is they have a single function $('#div').myplugin({options}), and then they can do different functions by passing a string instead of an object $('#div').myplugin('performdifferenttask') which can in turn call a helper function that is hidden from the user.

    For an example look at http://jqueryui.com/demos/progressbar/#methods

    Here is an example that will hopefully alleviate your confusion:

    (function($) {
        $.fn.myplugin = function(options) {
            if(options == 'function1')
                function1();
            else if(options == 'function2')
                function2();
            else {
                //do default action
            }
        }
    
        function function1() {
            //do something
        }
    
        function function2() {
            //do something else
        }
    }
    

    Then in use:

    $.myplugin({option1: 4, option2: 6}); //does default behavior
    $.myplugin('function1'); //calls function1()
    $.myplugin('function2'); //calls function2()
    

提交回复
热议问题