I’m having trouble with this js code:
$('.downvoted').live('click',function(){
var ele = $(this);
var truc = ele.prev('.score_position');
$.post('ajax/vote.php', { vote :ele.attr('title') }, function(data) {
if(data == 'done'){
ele.removeClass('downvoted').addClass('downvote').html('<img src="images/down.png" />');
truc.html(eval(truc.html()+1));
}
});
return false;
});
so I have this same function 3 other times for downvoting, un-upvoting and upvoting. It works well except with one exception, if truc.html() is -1 then it goes to -11 instead of 0.
Any idea why it doesn’t work? (you guys can try it here: http://91.121.154.130/?sort=last&# with id:azerty pw:azerty)
Don’t use
eval()for this sort of work! UseparseInt,Number(...), or any of the other numerous ways of converting a value to a number in Javascript.Note the second parameter in the
parseIntfunction. This means you want the value passed into be parsed as a base-10 number. If you pass in a number starting with 0 into theparseIntfunction without specifying the radix you’ll get an unexpected and unwanted result.Or
Or even this:
This works because multiplying a string number by one results converts the variable to a number. Be careful– if the variable you multiply isn’t a valid number you’ll get
NaN!The reason you can’t simply do
truc.html(truc.html()+1);is because.html()returns a string value. If you add a number to a string in Javascript, the number is simply concatenated to the string, and no math is performed. (e.g. “-1” + “1” equals “-11”).