【问题标题】:Javascript, increment a counter on button clickJavascript,在按钮单击时增加一个计数器
【发布时间】:2012-10-30 23:47:45
【问题描述】:

在 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

    });

  });​

如何使两行的值显示相同?

【问题讨论】:

    标签: javascript counter increment


    【解决方案1】:

    你正在做一个后期增量。使其预增量:

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

      试试这个:

        $(function() {
          var //valueCount = $("counter").value(),
              counter = $("#counter"),
              addBtn = $("#add"),
              value = $("#counter").html();
      
      
          addBtn.on("click", function() {
      
            counter.html(++value);
            console.log(value);
            return
      
          });
      
        });
      

      看看这个link关于JavaScript中++的运算符描述。

      实际上只改变了一行;但是,如果您想测试它,这里是提琴手link

      【讨论】:

        【解决方案3】:

        使用

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

          你的意思是:

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

          【讨论】:

          • 我猜 '++' 必须在值前面!感谢您的帮助!
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多