从外部调用 jQuery 插件内部的函数

2022-01-11 00:00:00 jquery jquery-plugins javascript

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

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 插件

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

推荐答案

看看 关闭.

这是一个基本示例,说明 jQuery 插件中的闭包.

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

你可以在下面的 jsfiddle 看到另一个例子.

You can see another example at the following jsfiddle.

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

相关文章