17

我正在尝试研究如何从插件外部调用我的 jQuery 插件中的函数。我尝试过的代码不起作用。我确定我将不得不重组我的插件以允许这样做,但我不确定如何去做。在此示例中,我正在尝试访问该underline()功能。

jsFiddle

jQuery插件

(function($) {
    "use strict";

    $.fn.testPlugin = function(options) {

        // Settings
        var settings = $.extend({
            newText : "Yabadabado"
        }, options);

        return this.each(function(i, el) {            

            var init = function(callback) {
                if( $(el).attr("class") === "red" ) {
                    $(el).css("color","red");
                }

                $(el).text(settings.newText);

                if( callback && typeof(callback) === "function" ) {
                    callback();
                }
            };

            var underline = function() {
                $(el).addClass("underline");
            };

            init();
        });
    };

}(jQuery));

将插件分配给选择器

var doTest = $("#testItem").testPlugin({
    newText: "Scoobydoo"
});

var doNewTest = $("#newTestItem").testPlugin({
    newText: "kapow!"
});    

调用位于插件中的函数

$("#underline").click(function(e) {
    e.preventDefault();
    doTest.underline();
});
4

2 回答 2

31

看看 闭包

这是一个关于 jQuery 插件中闭包的基本示例。

$.fn.plugin = function() {

    return {
        helloWorld: function() {
            console.log('Hello World!');
        }
    }
};

// init plugin.
var test = $('node').plugin();

// call a method from within the plugin outside of the plugin.
test.helloWorld();

您可以在以下 jsfiddle 中看到另一个示例。

http://jsfiddle.net/denniswaltermartinez/DwEFz/

于 2013-08-12T14:22:30.490 回答
19

首先,我们需要了解构建 jQuery 插件的每个步骤,就像构建一个 javascript 插件(类),但除此之外我们还有一个 jQuery 类。

//We start with a function and pass a jQuery class to it as a 
//parameter $ to avoid the conflict with other javascript 
//plugins that uses '$ as a name
(function($){
    //We now append our function to the jQuery namespace, 
    //with an option parameter
    $.fn.myplugin = function(options) {
        //the settings parameter will be our private parameter to our function
        //'myplugin', using jQuery.extend append 'options' to our settings
        var settings = jQuery.extend({
            param:'value',
        }, options);
        //Define a reference to our function myplugin which it's 
        //part of jQuery namespace functions, so we can use later
        //within inside functions
        var $jquery=this;

        //Define an output object that will work as a reference
        //for our function
        var output={
            //Setup our plugin functions as an object elements
            'function1':function(param){
                //Call jQuery reference that goes through jQuery selector
                $jquery.each(function(){
                    //Define a reference of each element of jQuery 
                    //selector elements
                    var _this=this;
                });
                //This steps is required if you want to call nested
                //functions like jQuery.
                return output;
            },
            //If we want to make our plugin to do a specific operations
            //when called, we define a function for that
            'init':function(){
                $jquery.each(function(){
                    var _this=this;
                    //Note that _this param linked to each jQuery 
                    //functions not element, thus wont behave like 
                    //jQuery function.
                    //And for that we set a parameter to reference the
                    //jQuery element
                    _this.$this=$(this);

                    //We can define a private function for 'init'
                    //function
                    var privatefun=function(){}
                    privatefun();

                    //We can now do jQuery stuffs on each element
                    _this.$this.on('click',function(){
                        //jQuery related stuffs
                    });
                });
                //We can call whatever function we want or parameter
                //that belongs to our plugin
                output.function1("value");
            }
        };
        //Our output is ready, if we want our plugin to execute a
        //function whenever it called we do it now
        output.init();

        //And the final critical step, return our object output to
        //the plugin
        return output;
    };
//Pass the jQuery class so we can use it inside our plugin 'class'
})(jQuery);

现在使用我们的功能非常容易

<div class="plugintest">
    <span>1</span>
    <span>2</span>
    <span>3</span>
    <span>4</span>
</div>

<script>
    $(function(){
        var myplugin=$(".plugintest > span").myplugin({
            param:'somevalue'
        });
        myplugin.function1(1).function1(2).function1(3);
    });
</script>

简而言之,jQuery 插件和任何 Javascript 插件都只是关于参数范围。

小提琴版 https://jsfiddle.net/eiadsamman/a59uwmga/

于 2015-02-24T14:37:32.820 回答