1
(function($){
    $.fn.the_func = function() {

        function my_func(){
            alert('it works');
        }

        my_func();

        // other code

    };
})(jQuery);

$(window).load(function(){
    my_func(); // This way?
    $.the_func().my_func(); // Or this way? No?
    $.the_func.my_func(); // No?
    // ?
});

$(document).ready(function(){
    $('div').the_func();
});

この関数をラップする関数の外でどのように呼び出すことができますか?このコード例のよう
に呼び出したいと思います。 (window-load関数は単なる例です。) 。内の他の関数やコードを実行せずに、「どこでも」 から呼び出したい。しかし、私はの変数を使用したいと思います。 のパラメータに格納されている値を更新したい。my_func()

my_func()the_func()the_func()
my_func()the_func()

4

1 に答える 1

2

これは、私が通常プラグインを作成し、あなたの状況に適用できる方法の例です。

http://jsfiddle.net/pMPum/1/

(function ($) {
    function my_func(element) {
        console.log("it works: " + element.innerHTML);
    }

    var methods = {
        init: function (options) {
            console.log("from init");
            console.log("options for init: " + JSON.stringify(options));
            my_func(this);
        },

        my_func: function (options) {
            console.log("from my_func");
            console.log("options for my_func: " + JSON.stringify(options));
            my_func(this);
        }
    };

    $.fn.the_func = function (method) {
        var args = arguments;
        var argss = Array.prototype.slice.call(args, 1);

        return this.each(function () {
            if (methods[method]) {
                methods[method].apply(this, argss);
            }
            else if (typeof method === "object" || !method) {
                methods.init.apply(this, args);
            }
            else {
                $.error("Method " + method + " does not exist on jQuery.the_func");
            }
        });
    };
})(jQuery);

$(document).ready(function () {
    $("div").the_func({    // Same as passing "init" and { } as params
        test: "testing"
    });
});

my_func呼び出すことができるスコープ内にジェネリック関数を作成した方法に注目してください。のmy_funcメソッドはmethods、プラグイン構文を通じて世界に公開されるもので.the_func()あり、my_func関数はプライベートであり、直接アクセスすることはできません。

さまざまなメソッドを呼び出すための構文は、ほとんど/多くのjQueryプラグインと同じです。

于 2012-11-29T14:44:04.597 に答える