0

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.

4

2 回答 2

1

我会通过将点击计数存储在单个元素上来解决这个问题,如下所示:

$('.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.');

    });

工作小提琴

这是最好的方法吗?

于 2013-10-30T16:47:36.500 回答
0

这对你来说是一个非常简单的例子和​​很好的例子:

$('.clickme').on('click', function () {
          var count = parseInt($(this).data('click'), 10) || 0;
          count++;
          $(this).data('click',count);
          alert(count);    
        });

这里:JSFiddle

于 2013-10-30T17:00:43.627 回答