我遇到了问题,经过多次搜索后,我仍然锁定了。我遵循了许多关于如何创建jQuery插件的教程(从jQuery的教程“Authoring”开始,该教程不再存在,但建议按照创建插件的方式),并且没有指定插件的其他公共方法中的访问设置。 / p>
让代码说话:
;(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,只需保存/检索设置var,使用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 !"}'
答案 0 :(得分:1)
尝试将init
方法更改为如下所示:
var $this = $(this);
$this.data('test', $.extend(true, {}, $.fn.test.defaultSettings, options || {}));
console.log($this.data('test'));
然后在您的更新中,您可以访问它:
console.log($this.data('test'));
我使用“test”的原因是因为这是你插件的名称。适当改变,以便不会有任何覆盖或其他冲突。