jQuery插件:访问其他公共方法中的设置

jQuery插件:访问其他公共方法中的设置,jquery,jquery-plugins,Jquery,Jquery Plugins,我有一个问题,经过多次搜索,我仍然锁定。我学习了很多关于如何创建jQuery插件的教程(从jQuery的教程“Authoring”开始,它已经不存在了,但建议按照下面的方法创建插件),并且在插件的其他公共方法中没有指定访问设置 让代码说话: ;(function($, window, document, undefined) { var methods = { init: function(options) { return this.each(

我有一个问题,经过多次搜索,我仍然锁定。我学习了很多关于如何创建jQuery插件的教程(从jQuery的教程“Authoring”开始,它已经不存在了,但建议按照下面的方法创建插件),并且在插件的其他公共方法中没有指定访问设置

让代码说话:

;(function($, window, document, undefined) {

    var methods = {
        init: function(options) {
            return this.each(function() {
                var $this = $(this);
                $this.settings = $.extend(true, {}, $.fn.test.defaultSettings, options || {});
                console.log($this.settings);
            });
        },
        update: function() {
            return this.each(function() {
                var $this = $(this);
                console.log($this.settings);
            });
        }
    };

    $.fn.test = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.inlineEdit');
        }
    };

    $.fn.test.defaultSettings = {
        'test': "ok"
    };
})(jQuery, window, document);
基本上,我只是想:

$('body').test(); // displays 'Object {test: "ok"}'
$('body').test('update'); // displays 'undefined'
那么,我如何访问更新功能中的设置

编辑:多亏了kalley,只需使用data()保存/检索设置变量即可:

var methods = {
    init: function(options) {
        return this.each(function() {
            var $this = $(this);
            $this.settings = $.extend(true, {}, $.fn.test.defaultSettings, options || {});
            $this.data("test", $this.settings);
            $this.settings.test2 = "that rocks !";
            console.log($this.settings);
        });
    },
    update: function() {
        return this.each(function() {
            var $this = $(this);
            $this.settings = $this.data("test");
            console.log($this.settings);
        });
    }
};
现在:

$('body').test(); // displays 'Object {test: "ok", test2: "that rocks !"}'
$('body').test('update'); // displays 'Object {test: "ok", test2: "that rocks !"}'

尝试将
init
方法更改为如下所示:

var $this = $(this);
$this.data('test', $.extend(true, {}, $.fn.test.defaultSettings, options || {}));
console.log($this.data('test'));
然后在您的更新中,您可以通过以下方式访问它:

 console.log($this.data('test'));

我之所以使用“test”是因为这是你插件的名字。根据需要进行更改,希望不会出现任何覆盖或其他冲突。

可能重复不,它不会处理相同的事情。谢谢,这就是我搜索的内容!