写一个计数器来计算点击次数

Writing a counter to count the number of clicks

我的网站上有两个按钮。下一个和上一个。我想编写一个代码来增加每次单击下一个时的值,并减少每次单击上一个时的值。我希望该值显示在输入中。但是input中显示的值始终为0,不会随着点击而改变。

这是我的代码:

function count(){
    var $counter=0;
    $(".next-button").click(function() {
         $counter=$counter+1;
    });
    $(".previous").click(function() {
        $counter=$counter-1;
    });
    return $counter;
}

document.getElementById('counter').value =count();

您不需要在此函数中使用 return。事实上,您根本不需要函数。而是在更新时显示 counter

var $counter=0;
$(".next-button").click(function() {
     $('#counter').val($counter++);
});
$(".previous").click(function() {
    $('#counter').val($counter--);
});

您应该在每次更改时更新元素中的值:

(function count(){
    var counter=0,
        $container = $('#counter');
    $(".next-button").click(function() {
        $container.text(++counter);
    });
    $(".previous").click(function() {
        $container.text(--counter);
    });
})();

全局声明计数器,因此它只会初始化一次

var $counter=0;
  var count=document.getElementById('counter');
     $(".next").click(function() {
          count.value=++$counter;
     });
     $(".pre").click(function() {
         count.value=--$counter;
         
     });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<button class="next">next</button>
 <button class="pre">pre</button>
 <input type="text" id="counter" value="0" />

您的代码包含多个错误。您在 count() 函数中将变量重置为 0,并将 click() 函数放在函数中。

var counter=0;
function count(){
    return counter;
}

$(".next-button").click(function() {
    counter = counter+1;
});
$(".previous").click(function() {
    counter = counter-1;
});

$('#counter').val(count());
// or 
$('#counter').val(counter);

我假设 $('#counter') 是一个输入文本框。

p.s。变量不需要前缀 $。扩展 reading 关于这个匈牙利符号:何时使用,何时不使用。

你可以这样做:

var $counter = 0;

$(".next-button").click(function() {
    $counter = $counter + 1;
    refreshCount();
});
$(".previous").click(function() {
    $counter = $counter - 1;
    refreshCount();
});

function refreshCount() {
    document.getElementById('counter').value = $counter;
}

//init
refreshCount();

首先,您的赋值表达式实际上是 运行 计数函数。

document.getElementById('counter').value =count();

计数函数return0.

(function() {
  var $counter = 0;

  var add = function() {
    $counter ++;
    setCounterValue();
  }

  var del = function() {
    $counter --;
    setCounterValue();  
  }

  var setCounterValue = function() {
    document.getElementById('counter').value = $counter;        
  }

  $(".next-button").bind("click", add);

  $(".previous").bind("click", del);
})()