This is my first question here at SO. Basically I have a huge number of elements on page and I want to count and display the number of times a user clicks each of them. But for that I would need to define variables for each element.
Isn't there an easier way?
For one element:
var counter = 0;
$('.container').on("click", function(){
counter = counter+1;
$(this).find('.tag').html(counter);
});
解决方案
You can store data with each element counting the number of times each was clicked.
$(function(){
$('.container').click(function(){
if ($(this).data('count')) { // already been clicked
$(this).data('count', $(this).data('count') + 1); // add one
} else { // first click
$(this).data('count', 1); // initialize the count
}
$(this).html($(this).data('count')); // show it
});
});