简体   繁体   English

通过按下按钮计算点击次数

[英]Counting the number of clicks by pressing a button

I am new to coding and using Lab.JS for a project.我是一个项目的编码和使用 Lab.JS 的新手。 I have a button that when pressed, it counts the number of clicks made and then logs it in the console.我有一个按钮,按下它时,它会计算点击次数,然后将其记录在控制台中。 It is important that the number of clicks isn't shown on screen when the button is pressed and is hidden away from the person pressing the button.重要的是,当按下按钮时,点击次数不会显示在屏幕上,并且不会被按下按钮的人看到。 I just want the clicks to be counted, but I am not sure how to fix the code iAny help would be appreciated.我只想计算点击次数,但我不确定如何修复代码 iAny 帮助将不胜感激。

 var clicks = 0; trigger = function() { clicks += 1; document.getElementById("trigger").innerHTML = clicks; } console.log(clicks)
 <button class="trigger" id="trigger" onclick="trigger()">SUBMIT</button>

Please try this code.请试试这个代码。

  <body>
    <button onclick="trigger()">Click Me</button>
    <script>
      // Initiate a global variable a
      var a = 0;
      function trigger() {
        a++;
        console.log(a);
      }
    </script>
  </body>

As long as you make your variable global.只要您将变量设为全局变量。 It's value will be save only for that page until user will close the page or tab.它的值将只保存在该页面上,直到用户关闭页面或选项卡。

Instead of updating the HTML of button you can add a new div and update it with count like:您可以添加一个新的 div 并使用计数更新它,而不是更新按钮的 HTML,例如:

 var clicks = 0; trigger = function() { clicks += 1; document.getElementById("display").innerHTML = clicks; }
 #display { padding: 20px; margin: 10px; font-size: 2rem; }
 <div id="display">0</div> <button class="trigger" id="trigger" onclick="trigger()">SUBMIT</button>

If you didn't want to have a global clicks variable you could encapsulate it within the function itself, and return a closure .如果您不想拥有全局clicks变量,您可以将其封装在函数本身中,并返回一个closure

 // Default `clicks` to zero function trigger(clicks = 0) { // Return a new function that increases // the click count return function () { console.log(++clicks); } } // Call trigger and assign the returned function // to a new variable called counter const counter = trigger(); // Move the inline `onclick` listener to the JS // Call `counter` when the button is clicked const button = document.querySelector('.trigger'); button.addEventListener('click', counter, false);
 <button class="trigger">SUBMIT</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM