【问题标题】:jQuery mouseclick counter - How to reset?jQuery 鼠标点击计数器 - 如何重置?
【发布时间】:2017-02-09 14:47:56
【问题描述】:

我正在尝试创建一个每次用户单击鼠标时都会计数的网站。我已经关闭了该部分,但我还需要包含一个重置按钮,在用户单击它后,它会从 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')
});

我需要他们能够单击“按钮”并且计数将重置。有什么建议吗?

【问题讨论】:

  • 第一个计数器 = 0;然后 $("#mouseclick").text("鼠标点击总数:" + counter); =)
  • 最后的“$('button')”是什么?
  • 在您的按钮点击事件中,只需设置counter=0

标签: javascript jquery events click reset


【解决方案1】:

您没有重置计数器。见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");
});

【讨论】:

  • 谢谢!我以为我昨晚已经这样做了,但回想起来我把 var counter=0;而不仅仅是 counter=0;。谢谢!
  • 实际上,如果我可以问 - 为什么 var counter=0;不工作,而不是 counter=0;?是不是因为变量已经定义了所以变得多余了?
  • 如果使用var关键字重新定义变量,通常会抛出错误。
【解决方案2】:

只需在 $('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");
});

【讨论】:

  • 天哪.... 太容易了。我认真地认为我已经尝试了一切。完全想多了,哈哈。谢谢!!
猜你喜欢
  • 2023-03-29
  • 2017-03-15
  • 2015-11-07
  • 1970-01-01
  • 2014-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-05
相关资源
最近更新 更多