Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

javascript - Calling a function inside a jQuery plugin from outside

I am trying to work out how to call functions within my jQuery plugin from outside the plugin. The code I have tried is not working. I'm sure I will have to restructure my plugin to allow this, but I'm not sure how to. In this example, I'm trying to access the underline() function.

jsFiddle

jQuery plugin

(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));

Assign the plugin to selectors

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

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

Call a function that is located within the plugin

$("#underline").click(function(e) {
    e.preventDefault();
    doTest.underline();
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Take a look at closures.

Here is a basic example of what a closure looks like in a jQuery plugin.

$.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();

You can see another example at the following jsfiddle.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...