Javascript, increment a counter on button click

女生的网名这么多〃 提交于 2019-12-01 06:25:09

问题


In javascript, I want to make a counter that increases the value when you click a button.

When I click the add button the first time, the number doesn't increase.

But when I print the value to the console, the result increases.

The fiddle: 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

    });

  });​

How do I make the value show the same for both lines?


回答1:


You are doing a Post Increment. Make it pre-increment:

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

Explanation:

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


do you mean:

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



回答3:


use

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

LIVE 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

    });

  });



回答4:


Try this:

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


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

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

    });

  });

Take a look in this link about the operator description of ++ in JavaScript.

Only one line actually changed; however, here is the fiddler link if you want to test it.



来源:https://stackoverflow.com/questions/13328717/javascript-increment-a-counter-on-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!