Javascript,单击按钮时增加计数器

2023-11-29

在javascript中,我想制作一个计数器,当您单击按钮时该计数器会增加值。

当我第一次单击添加按钮时,数字不会增加。

但是当我将值打印到控制台时,结果会增加。

小提琴:http://jsfiddle.net/techydude/H63As/

  $(function() {
    var //valueCount = $("counter").value(),
        counter = $("#counter"),
        addBtn = $("#add"),
        value = $("#counter").html();

      addBtn.on("click", function() {

      counter.html(value ++);  //this value is not incremented.
      console.log(value);      //this value gets incremented.
      return

    });

  });​

如何使两条线的值显示相同?


您正在执行后增量。使其预自增:

addBtn.on("click", function() {
  counter.html(++value);
  console.log(value);
  return
});

解释:

// Increment operators
x = 1;
y = ++x;    // x is now 2, y is also 2
y = x++;    // x is now 3, y is 2

// Decrement operators
x = 3;
y = x--;    // x is now 2, y is 3
y = --x;    // x is now 1, y is also 1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Javascript,单击按钮时增加计数器 的相关文章

随机推荐