简体   繁体   English

如何使用匹配所有元素的jQuery选择器跟踪多个元素的点击计数?

[英]How can I track click counts for multiple elements with a jQuery selector that matches all of the elements?

I have a set of buttons with the same clickme class: 我有一组具有相同clickme类的按钮:

<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类的单击处理程序:

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

    });

Working fiddle . 工作提琴

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 这里: JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM