如何在点击时增加计数器

How can I increase a counter on click?

本文关键字:增加 计数器      更新时间:2023-09-26

我想要一个在点击按钮时增加的计数器。我尝试了以下代码,但打印的值保持不变:

$(document).ready(function () {
    $("#gonder").click(function() {
        var baslik = document.title;
        var sayi = 1;
        var sayi1 = sayi++;
        document.title = '(' +sayi+ ')' + baslik;
    });
});

我该怎么做?

我能想到的最简单的

<button>clicked 0 times</button> 
var count = 0;
$('button').click(function(){
     count++;
    $(this).text("clicked "+count+" times");
});

小提琴在这里http://jsfiddle.net/PKcrd/

以下是我在闭包上写的一篇相当详细的文章,使用你的确切目标作为稻草人(呃…问题)

http://jondavidjohn.com/blog/2011/09/javascript-event-handler-persistance-with-closures

基本上你可以用两种方法中的一种。

  • 在事件处理程序的作用域之外创建一个计数器变量。

    var count = 0;
    element.onclick = function() {
        count++;
    };
    
  • 使用闭包为每个元素提供它自己的唯一计数器,该计数器包含在事件处理程序本身中。我在博客文章中详细介绍了这一点。

您需要在函数之外初始化计数器。你每次点击都会清除它。

var sayi = 1;
$(document).ready(function () {
    $("#gonder").click(function() {
    var baslik = document.title;
    sayi++;
     document.title = '(' +sayi+ ')' + baslik;
    });
});
var clickCounter = 0;
$(document).ready(function () {
    $("#gonder").click(function() {
    var baslik = document.title;
    var sayi = 1;
    clickCounter++;
    document.title = '(' +sayi+ ')' + baslik;
});
});

我想这就是你想要的:

var sayi = 1;
var baslik = document.title;
$("#gonder").click(function() {
    document.title = '(' + (++sayi) + ')' + baslik;
});​

您可以尝试:

<button class="counter">I have been clicked 0 times</button> 
<script type="text/javascript">
    var count = 0;
    $('button.counter').click(function(){
        count++;
        $(this).text("clicked "+count+" times");
    });
</script>

这是我能想到的最简单的。

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<button id="btn" onclick="f1();">Button</button>
<p id="demo"></p>
<script>
var count=0;
function f1()
{
    document.getElementById("demo").innerHTML=count;
    count++;
}
</script>
</body>
</html>