Okay, here are several problems, and I understand what you want to achieve but maybe you should likewise place a Minimum, complete and verifiable to make it more explicit and we can see the execution of the problem.
For what you want to do, it may be as simple as placing an attribute in your elements to identify them or relating them to the buttons that execute the script.
The first problem that I see is that it is an interpretation error, since you put var idProducto = $(this).attr("idProducto");
. If you want to get the attribute of a
element you just have to place the name that identifies the attribute, either rel, id, class, etc.
and not the name that you give this attribute itself, being as follows var idProducto = $(this).attr("id");
The second problem is that you are getting the attribute of $(this)
within a function that is running in your class .contador
, so you are always getting the id of the counter element, not the elements you want, this is correct if you want to get the id of the element that is currently being pressed.
The third problem is that probably if you are only launching a console.log()
you are not updating the information in the DOM, so if you are receiving an error of a sum or parse will not update, this is nothing else a data.
And finally the slightly weird sum that you use from the idProduct + the id of the element. You are complicating a lot to relate elements, that is why I propose the following logic:
Place an attr rel on your buttons that matches the id of your elements:
<div>
<h1 id="elemento1" class='contador'>0</h1>
<button rel="elemento1" class="boton">like</button>
</div>
<div>
<h1 id="elemento2" class='contador'>0</h1>
<button rel="elemento2" class="boton">like</button>
</div>
<div>
<h1 id="elemento3" class='contador'>0</h1>
<button rel="elemento3" class="boton">like</button>
</div>
Activate the script with click
Here it is only necessary to manage the sum by a variable and identify which button is running through the attr rel to pass the information to your element that matches its id.
$("button").click(function(){
var relProducto = $(this).attr("rel");
//var idProducto = $(".contador").attr("id"); -- No es necesario.
var currentLikes = $("#"+relProducto).html();
currentLikes = parseInt(currentLikes);
currentLikes++;
$("#"+relProducto).html(currentLikes); // Actualiza la informacion de otra manera siempre sera el mismo numero.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h1 id="elemento1" class='contador'>0</h1>
<button rel="elemento1" class="boton">like</button>
</div>
<div>
<h1 id="elemento2" class='contador'>0</h1>
<button rel="elemento2" class="boton">like</button>
</div>
<div>
<h1 id="elemento3" class='contador'>0</h1>
<button rel="elemento3" class="boton">like</button>
</div>
I hope it helps you!