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

时间:2014-06-06 06:03:30

标签: javascript

我有一个页面,我想计算按钮的点击次数。数字显示在该按钮下方。

我试图搜索并找到了这个。我认为这不会计算总点击次数: Keeping track of number of button clicks

我熟悉javascript代码,所以任何帮助都会有用。

4 个答案:

答案 0 :(得分:4)

HTML代码:

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

JS代码:

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

答案 1 :(得分:2)

假设你的html是:

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

现在功能是:

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

答案 2 :(得分:0)

您可以这样做:

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

    }
  </script>

或者您可以添加事件列表器

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
});

答案 3 :(得分:0)

HTML:

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

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>