I have a set of buttons with the same clickme
class:
<button class="clickme">Click Me 1</button>
<button class="clickme">Click Me 2</button>
<button class="clickme">Click Me 3</button>
I also have a click handler for the clickme
class:
$('.clickme').on('click', function () {
// do stuff
});
How can I keep track of click counts for each individual button in this scenario?
Note: I've provided my own answer below, but I'm not sure if mine is the best solution. I think I could improve the brevity.
I would approach this problem by storing the click count on the individual elements like this:
$('.clickme').on('click', function () {
var that = $(this);
if (typeof (that.data( 'clickCount')) === 'undefined') {
that.data( 'clickCount', 1);
} else {
var clickCount = that.data( 'clickCount');
clickCount++;
that.data( 'clickCount', clickCount);
}
alert(that.text() + ' clicked ' + that.data( 'clickCount') + ' times.');
});
Is this the best approach?
This would be very simple exaple and good example for you:
$('.clickme').on('click', function () {
var count = parseInt($(this).data('click'), 10) || 0;
count++;
$(this).data('click',count);
alert(count);
});
HERE : JSFiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.