How to track click events on individual dom elements using jQuery and update their click counter accordingly?

时间:2016-04-04 16:45:06

标签: javascript jquery javascript-events event-handling

I am trying to track the number of clicks on 2 images using the same method. Below is the code that I've written to achieve the same-

$(document).ready(function () {
    var $foo= $('#foo'),
    $bar= $('#bar'),
    fooCount1 = 0,
    barCount2 = 0,
    count;

  function elemClicked (e) {
    count = e.data.count;
    count++;
    console.log(count);
    $(this).siblings('.counter').html(count);
  }

  $foo.click({count: fooCount1 }, elemClicked );
  $bar.click({count : barCount2 }, elemClicked );

})

And this is what the HTML looks like:

<div class="elems">
  <img class="pic" src="/path/img1.jpg" id="foo" alt="foo">
  <div class="counter"></div>
</div>
<div class="elems">
  <img class="pic" src="/path/img2.jpg" id="bar" alt="bar">
  <div class="counter"></div>
</div>

The counter doesn't get incremented for every click. How can increment the counter on every click? Also, is there a more elegant way to achieve what I am trying here?

1 个答案:

答案 0 :(得分:0)

$(".elems .pic").click(function() {
var incClick	= typeof($(this).attr("d-click"))=="undefined" ? 0 : $(this).attr("d-click");
  incClick	= parseInt(incClick);  
  incClick++;
  $(this).attr("d-click", incClick);
  $(this).next().html(incClick);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="elems">
  <img class="pic" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150" id="foo" alt="foo">
  <div class="counter"></div>
</div>
<div class="elems">
  <img class="pic" src="http://placehold.it/350x150" id="bar" alt="bar">
  <div class="counter"></div>
</div>

Above is the pretty simple code, through which you trigger click count easily.

every time a pic is click, the current pic holds an attribute named d-click with incremented value. and the same is represented under .html()