Implementing the upvote / downvote system in Javascript, but cannot get math right

var $arrow       = $(this);
var $sibling     = $arrow.siblings('span.arrow');
var $score       = $arrow.siblings('span.score');

var vote         = $arrow.hasClass('up') ? 'up' : 'down';
var alreadyVoted = $sibling.hasClass('voted');

if (!USER_LOGGED_IN)
{
    alert('You must be logged into vote');
}
else if (!$arrow.hasClass('voted'))
{
    if (alreadyVoted)
        $sibling.removeClass('voted');

    $arrow.addClass('voted');
    $score[0].innerHTML = parseInt($score[0].innerHTML) + ((vote == 'up') ? 1 : -1);
}

I have an upvote and downvote button. Next to these buttons is displayed the โ€œcurrent ratingโ€, which I would like to increase / decrease when giving a voice.

For example, if they load the page and see it 200. When they are flipped, the score changes to 201. When they decrease, the rating should be changed to 199. What for? Because if they lower the level after survival (change their minds), then the vote should go from the initial assessment. Not the new score they created by running.

Basically, if they move forward and then down, the valuation is currently returning to the original account. Their voice is not emphasized.

, ...

+5
3

:

parseInt($score[0].innerHTML) + ((vote == 'up') ? 1 : -1);

:

parseInt($score[0].innerHTML) + ((vote == 'up') ? 1 : -1) + ((alreadyVoted) ? ((vote == 'up') ? 1 : -1) : 0);

, .

+3

, , . , +1. () , n + 1 - 1 n. , .

0

, ( = 1), , , vote = -1 vote = 0 ( StackOverflow). , script, - :

var voteValue = parseInt($score[0].innerHTML, 10);
if (alreadyVoted) {
    $sibling.removeClass('voted');
    // Undo the previous vote
    voteValue += $sibling.hasClass('up') ? -1 : 1;
}

// Apply the new vote
$arrow.addClass('voted');
voteValue += (vote == 'up') ? 1 : -1;
$score[0].innerHTML = voteValue;

, , "" "" (, SO), :

if (alreadyVoted)
    $sibling.removeClass('voted');

$arrow.addClass('voted');
$score[0].innerHTML = vote == 'up' ? 1 : -1;

... since there is no need to add / subtract at all.

0
source

All Articles