In the span loop, there is an initialized variable 'a' with the value '0'. https://jsfiddle.net/k99yoL10/1 at the event of a click this variable increases by 1. Can I make it so that when I click on the black span I reset the variable in the first span?

$('span').each(function(){ var a=0; $(this).click(function(){ alert(a); a++; }); }); 
 span{ display:inline-block; width:70px; height:50px; background: red; } span:last-of-type{ background: #000; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span></span> <span></span> 

  • do you need to count the number of clicks for each span separately? In general, you can always write values ​​in the data- attributes - teran

1 answer 1

We enter the number not of a variable, but with the prop property and when clicking on the span reset the value of the neighbors:

 $('span').each(function() { $(this).prop('a', 0).click(function() { var a = $(this).prop('a'); alert( a ); // Прибавляем +1 и стираем у соседних $(this).prop('a', a + 1).siblings('span').prop('a', 0); }); }); 
 span { display: inline-block; width: 70px; height: 50px; background: red; } span:last-of-type { background: #000; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span></span> <span></span>