简体   繁体   中英

Javascript counter not incrementing correctly

I am trying to implement a counter in javascript that increments up when a thumbs up button is clicked, and down when the thumbs down is clicked. However, for some reason the first time the user clicks the thumbs down button the counter increments up a single time, after which it begins to increment correctly (down). Can someone have a look over my code and see what's causing this? Code as follows:

<script type="text/javascript">
var counter1 = 0;
</script>

<div class="pastel-vote-block">
  <img class="thumbup" onclick="document.getElementById('tallyone').innerHTML = counter1++" src="img/thumb-up-dark.png" height="32" width="32" alt="thumb up">
  <p class="tally" id="tallyone">0</p>
  <img class="thumbdown" onclick="document.getElementById('tallyone').innerHTML = counter1--" src="img/thumb-down-dark.png" height="32" width="32" alt="thumb down">
</div>

If you place the ++ operator after the variable, counter1 will be incremented after being assigned to innerHTML.

Try with ++counter1 and --counter1 as this will increment before the operator assignment and result in the expected output.

<script type="text/javascript">
var counter1 = 0;
</script>

<div class="pastel-vote-block">
  <img class="thumbup" onclick="document.getElementById('tallyone').innerHTML = ++counter1" src="img/thumb-up-dark.png" height="32" width="32" alt="thumb up">
  <p class="tally" id="tallyone">0</p>
  <img class="thumbdown" onclick="document.getElementById('tallyone').innerHTML = --counter1" src="img/thumb-down-dark.png" height="32" width="32" alt="thumb down">
</div>

OP used incement and decrement operators incorrectly

var a = 10, b;

b = a++; // b will be 10, a will be 11

var a = 10, b;

b = ++a; // b will be 11, a will be 11

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM