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

我不确定您为什么要访问插件 var,您应该已经可以访问调用刷新方法的元素。

于 2012-08-20T15:28:54.500 回答