当您在jQuery插件中设置计数器时,它将按插件的每个实例设置。例如
$.myPlugin(".one");
$.myPlugin(".two");
$.myPlugin = function (el) {
var counter = 0;
$(el).click(function () {
counter++;
console.log(counter);
});
};会启动两个计数器。(在这里试试)但是,我希望每个元素都有一个计数器,而不是每个实例。所以,在小提琴里我总共需要三个柜台。(请注意,元素的长度不是预先设置的,因此必须是动态的。)我考虑在计数器的名称中添加一个唯一的值,但我不完全确定什么值足够具体,这样就不会有任何重复。
也许是一个for循环和一个整数来区分,例如counter-1,counter-2,counter-3?但是如何循环插件的实例呢?换句话说,当我在三个元素上调用插件两次时,如何确保只得到三个唯一的计数器?
发布于 2015-05-30 08:21:14
您可以使用.data()来自定义与您的elemet关联的
存储与匹配元素关联的任意数据,或在命名数据存储处返回匹配元素集中的第一个元素的值。
代码
$.myPlugin = function (el) {
$(el).click(function () {
var counter = $(this).data('counter') || 1;
console.log(counter);
$(this).data('counter', ++counter);
});
};演示
我个人希望这样
$.fn.myPlugin = function () {
this.click(function () {
var counter = $(this).data('counter') || 1;
console.log(counter);
$(this).data('counter', ++counter)
});
};
$(".one").myPlugin();
$(".two").myPlugin();演示
发布于 2015-05-30 08:15:55
使用自定义data-属性设置计数器
$('button').each(function(){
$(this).attr('data-counter', 0);
$(this).click(function () {
var counter = parseInt($(this).attr('data-counter'));
counter++;
console.log(counter);
$(this).attr('data-counter', counter);
});
});演示
发布于 2015-05-30 08:24:09
使用.data()
试试这个例子:
$.myPlugin(".one");
$.myPlugin(".two");
$.myPlugin = function (el) {
$(el).on('click', function () { // using .on instead of .click to handle dynamicaly added elements
var counter = parseInt($(this).data('counter')); // using .data() function of jquery to get value from element, it uses data-counter attribute
counter++; // iterating
$(this).data('counter', counter); // setting back counter with iterated value
});
};https://stackoverflow.com/questions/30543832
复制相似问题