jQuery 鼠标点击计数器 - 如何重置?

jQuery mouseclick counter - How to reset?

我正在尝试制作一个网站,每次用户单击鼠标时都会计数。我有那个部分,但我还需要包括一个重置按钮,在用户点击它后,鼠标点击计数器从 0 开始。

我想不通 - 如果我移动 var = 0 关于文档就绪,它会重置,但在单击按钮后,计数器永远不会超过 1。我不确定该怎么做。

我的脚本 -

$(document).ready(function(){
    console.log("Here");


    $(document).click(function(e) {
        $('#location').append("("+e.clientX+", "+e.clientY+")<br>");
    });

    var counter = 0;
    $(document).click(function(e) {
        counter++;
        $("#mouseclick").text("Total mouse clicks: " + counter);
    });

    $('button').click(function(e) {
        e.stopPropagation();  // stop the event from propagating up the visual tree
        $('#location').text("");
        $("#mouseclick").text("Total mouse clicks: 0");
    });

    $('button')
});

我需要他们能够点击 'button' 并且计数会重置。有什么建议吗?

您没有重置计数器。参见 this fiddle

$(document).ready(function(){
  console.log("Here");


$(document).click(function(e) {
  $('#location').append("("+e.clientX+", "+e.clientY+")<br>");
});

var counter = 0;
$(document).click(function(e) {
  counter++;
  $("#mouseclick").text("Total mouse clicks: " + counter);
});

$('button').click(function(e) {
  e.stopPropagation();  // stop the event from propagating up the visual tree
  $('#location').text("");
  counter = 0;
  $("#mouseclick").text("Total mouse clicks: 0");
});

只需在 $('button').click() 事件中添加 counter=0。

$('button').click(function(e) {
   counter=0;
   e.stopPropagation();  // stop the event from propagating up the visual tree
   $('#location').text("");
   $("#mouseclick").text("Total mouse clicks: 0");
});