Pergunta

I am trying to create a thumbs up/down rating demo http://jsfiddle.net/HfNL9/1/

var ups = 0;

$('.rating .voteup').on('click', function () {
    var currentId = $(this).attr('href');
    ups = ups + 1;
    $(currentId + ' > .up').html(ups);

    return false;
});

var downs = 0;

$('.rating .votedown').on('click', function () {
    var currentId = $(this).attr('href');
    downs = downs + 1;
    $(currentId + ' > .down').html(downs);

    return false;
});

However it keeps the count for elements with different ids, please see the fiddle (click both thumbs ups or thumbs down to see what I mean). How do I resolve this?

Foi útil?

Solução

Try this

$('.rating .voteup').on('click', function () {
    var up = $(this).closest('div').find('.up');
    up.text(parseInt(up.text()) + 1);
    return false;
});
$('.rating .votedown').on('click', function () {
    var down = $(this).closest('div').find('.down');
    down.text(parseInt(down.text()) + 1);
    return false;
});

DEMO

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top