简体   繁体   English

用于计算按钮点击次数的 Javascript 代码

[英]Javascript code to count number of clicks on a button

I have a page where i want to count the number of clicks on a button.我有一个页面,我想计算一个按钮的点击次数。 and the numbers are shown just below that button.数字显示在该按钮的正下方。

I tried to search and found this.我试图搜索并找到了这个。 I think this will not count the total number of clicks: Keeping track of number of button clicks我认为这不会计算总点击次数: 跟踪按钮点击次数

I am familiar with javascript code, so any help would be useful.我熟悉 javascript 代码,所以任何帮助都会有用。

HTML Code : HTML代码:

  <button onclick="myFunction()">Try it</button>

JS Code : JS代码:

 var inc=0;
 function myFunction() {
    inc=inc+1;
    alert(inc);    
 }

Suppose your html is:假设你的 html 是:

<div id="showCount"></div>
<input type="button" id="btnClick" value="Click me" onclick="CountFun();/>

Now the function is:现在的功能是:

   <script>
    var cnt=0;
    function CountFun(){
     cnt=parseInt(cnt)+parseInt(1);
     var divData=document.getElementById("showCount");
     divData.innerHTML="Number of Downloads: ("+cnt +")";//this part has been edited

    }
  </script>

You can do it this way:你可以这样做:

  <script>
    var cnt=0;
    function CountFun(){
     cnt++
     var divData=document.getElementById("showCount");
     divData.innerHTML="Number of Downloads: ("+cnt +")";//this part has been edited

    }
  </script>

Or you can add event listner或者您可以添加事件监听器

documet.getElementById('[id of the button]').addEventListener('click', function(){
         cnt++
         var divData=document.getElementById("showCount");
         divData.innerHTML="Number of Downloads: ("+cnt +")";//this part has been edited
});

HTML: HTML:

 <button id='click-me'>Click me please!!</button>
 <div id='showCount'></div>

JS Code: JS代码:

  <script>
      let count = 0;
      let btn = document.querySelector('#click-me');
      let divSection = document.getElementById('showCount');
      btn.addEventListener('click', (e)=>{
        count++;
        divSection.innerHTML=`Number of Clicks are: ${count}`;
     });
  </script>

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

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