简体   繁体   中英

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.

HTML Code :

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

JS Code :

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

Suppose your html is:

<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:

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

JS Code:

  <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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