When you set a counter in a jQuery plugin it will be set per instance of the plugin. For instance
$.myPlugin(\".one\");
$.myPlugin(\".two\");
$.myPlugin = funct
Use custom data-
attributes to set a counter
$('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);
});
});
DEMO
Use .data()
Try this example:
$.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
});
};
You can use .data() to custom associated with your elemet
Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.
Code
$.myPlugin = function (el) {
$(el).click(function () {
var counter = $(this).data('counter') || 1;
console.log(counter);
$(this).data('counter', ++counter);
});
};
DEMO
I personally would like it this way
$.fn.myPlugin = function () {
this.click(function () {
var counter = $(this).data('counter') || 1;
console.log(counter);
$(this).data('counter', ++counter)
});
};
$(".one").myPlugin();
$(".two").myPlugin();
DEMO