0

jQuery拡張機能のメソッド間でデータを共有する方法を知りたいので、メソッドを呼び出すと、で定義されたおよび変数refreshを使用できます。pluginoptionsinit

ページごとにこれらのコントロールが複数あります。

これが私が持っているものの例です:

(function($) {
    var methods = {
        init: function(options) {
            var defaults = {
                defaultText: "Rating",
                maxRating: 5,
            };

            options = $.extend(defaults, options);

            return this.each(function() {
                var plugin = $(this);

                main($(plugin), options);
            });
        },

        refresh: function() {
            // I would like to be able to use the 'options' and 'plugin' variables defined in the init method
        }
    };

    function main(plugin, option) {
        // do main code stuff
    }
}(jQuery));
4

1 に答える 1

2

要素自体にデータを保存し、要素ごとにアクセスします。

(function ($) {

var methods = { // should probably expose this object in some way so it can be extended by other develoeprs or so that defaults can be changed

    defaults : {
        defaultText: "Rating",
        maxRating: 5,
    },

    init : function (options) {

        options = $.extend({}, methods.defaults, options);

        this.data("myPlugin", options);

        return this.each(function () {

            main($(this), options);

        });
    },

    refresh : function () {

        return this.each(function(){

            var options = $(this).data("myPlugin");

        });
                // I would like to be able to use the 'options' and 'plugin' variables defined in the init method
    }
};

function main(plugin, option) {

    // do main code stuff

}

})(jQuery);

プラグイン変数にアクセスする理由がわかりません。refreshメソッドが呼び出される要素にすでにアクセスできるはずです。

于 2012-08-20T15:28:54.500 に答える