Javascript计数器没有正确递增

时间:2015-11-03 17:13:25

标签: javascript html integer increment

我正在尝试在javascript中实现一个计数器,当单击一个拇指按钮时,该计数器会递增,而当单击拇指按下时,它会向下计数。但是,由于某种原因,用户第一次单击向下按钮时,计数器会向上递增一次,之后它会开始正确递增(向下)。有人可以查看我的代码,看看导致这种情况的原因是什么?代码如下:

<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>

3 个答案:

答案 0 :(得分:8)

如果将scala> implicitly[Substitutable[List[Int]]] <console>:14: error: could not find implicit value for parameter e: Substitutable[List[Int]] 运算符放在变量之后,则在分配给innerHTML后,counter1将递增。

尝试使用++++counter1,因为这会在运算符分配之前递增,并产生预期的输出。

答案 1 :(得分:0)

<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错误地使用了incement和decrement运算符

答案 2 :(得分:0)

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