JavaScript,点击按钮时增加计数器

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

    });

  });​

如何使两行的值显示相同?
4个回答

4

你正在使用后缀递增运算符,将其改为前缀递增运算符:

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

2
你的意思是:
addBtn.on("click", function() {
    counter.html(++value);
    return;          
});

1
“++” 应该放在值的前面!谢谢你的帮助! - TechyDude

1

使用

 value = parseInt($("#counter").html());

实时 jSFiddle

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


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

      counter.html(++value );
      console.log(value);
      return

    });

  });

1

试试这个:

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


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

      counter.html(++value);
      console.log(value);
      return

    });

  });

请查看此 链接,了解 JavaScript 中 ++ 运算符的操作说明。

实际上只有一行代码发生了变化;但是,如果您想测试它,这里是 Fiddler 链接


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接