4
我遇到問題,經過多次搜索後,我仍然鎖定。我遵循了許多關於如何創建jQuery插件的教程(從jQuery教程「Authoring」開始,它不再存在,但是推薦按照後面的方式創建插件),並且沒有任何關於插件的其他公共方法的訪問設置的規定。jQuery插件:在其他公共方法中的訪問設置
讓代碼說話:
;(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)使它完美:
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 !"}'
可能的重複http://stackoverflow.com/questions/1117086/how-to-create-a-jquery-plugin-with-methods – alkis
不,它不處理同樣的事情。 – Pierre