这是我的 jQuery 插件的虚构版本,但结构完全相同:
(function ($)
{
var initialized = false;
var element;
var counter = 0;
$.fn.myPlugin= function(action)
{
if (action === "increase")
{
increase(arguments[1]);
}
else if (!initialized)
{
settings = $.extend({
...
}, action);
initialized = true;
element = $(this);
return this;
}
else
{
console.error("Unknown function call.");
return;
}
};
var increase = function(amount)
{
counter += amount;
element.text(counter);
};
}(jQuery));
使用此代码,我可以像这样初始化我的插件:
$("#element").myPlugin(options);
我可以像这样调用增加方法:
$("#element").myPlugin("increase", 5);
但是,由于变量 initilized、element 和 counter,我无法在一页上的多个元素上初始化我的插件。 如何修改此代码,以便我可以在一个页面上多次使用它,而无需更改初始化和调用方法的方式?
最佳答案
我自己也做了同样的事情,一旦你知道怎么做,事情就会变得非常简单。
以这个简单插件为例...
$.fn.myPlugin = function() {
// plugin global vars go here
// do plugin stuff here
}
要修改它以在多个实例上工作,您只需在调用它时解析 this
...
$.fn.myPlugin = function() {
$(this).each(function() {
// plugin global vars go here
// do plugin stuff here
});
}
这样,当您将插件分配给单个实例或元素集合时,它就会起作用。
然后,要调用各个元素的方法,您只需指定正确的方法...
$("#element1").doMethod(1, 2, 3);
$("#element2").doMethod(4, 5, 6);
关于javascript - 转换 jQuery 插件以支持多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47220531/