gpt4 book ai didi

javascript - jQuery 扩展数据持久化

转载 作者:行者123 更新时间:2023-12-02 19:26:05 25 4
gpt4 key购买 nike

我想知道如何在 jQuery 扩展中的方法之间共享数据,因此当我调用 refresh 方法时,它能够使用 plugin optionsinit 中定义的变量。

每页有多个这样的控件。

这是我所拥有的示例:

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

最佳答案

将数据存储在元素本身上,然后按元素访问它。

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

我不确定您为什么想要访问插件变量,您应该已经有权访问调用刷新方法的元素。

关于javascript - jQuery 扩展数据持久化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12040483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com