Actually with the code you have it will have to be:
var spans = $('.click > span'); // ou somente $('.click span');
This is because you can not have duplicate IDs. That is: using $('#valorSpan');
will return only the first found.
If you change the HTML / PHP to use classes:
for ($j=0; $j < $total_prod; $j++){
echo "
<div>
<a href='#' class='click'>
<span class='valorSpan'> $preco </span>
</a>
</div>
";
}
then you can do:
var spans = $('.valorSpan');
In the question it talks about how to retrieve values from a
span
and the code that it uses in the event handler points to the ancora
$('#click')
looking for ID
Prém: Note that the CSS selector for ID is #
and class is .
.
I'm not sure why it uses an anchor <a>
there, I would do without anchor, only with span
. But keeping your HTML structure, changing only to 'class =' valueSpan 'here is a working code: link
$(document).ready(function () {
$('.click span').click(function (e) {
e.preventDefault();
pegarPreco = parseFloat(this.innerHTML);
alert(pegarPreco);
});
});
If, as indicated in the comment, you have more code inside the anchor and you need to get the value of the span, you can use this:
$(document).ready(function () {
$('.click').click(function(e) {
e.preventDefault();
pegarPreco = parseFloat($(this).find('span').html());
alert(pegarPreco);
});
});