简体   繁体   English

如何限制JavaScript中按钮的点击次数?

[英]How do I limit the number of clicks on a button in JavaScript?

I need to display the button Hour , 2 numbers in big font 0:0, and a button Minute . 我需要显示按钮Hourbig font 0:0的2个数字和一个Minute按钮。

The first number represents the hour, the second number represents the minute. 第一个数字表示小时,第二个数字表示分钟。

Whenever the user clicks the Hour button, the first number is increased by 1 , so that it goes like 0, 1, 2, 3, …, 23. 每当用户单击“ Hour按钮时,第一个数字都会增加1 ,因此它的值like 0, 1, 2, 3, …, 23.

If the hour number is 23 and the user clicks the hour button then the number goes back to 0 . 如果小时数是23 ,并且用户单击小时按钮,则该数字将返回0

Similarly, whenever the user clicks the “Minute” button, the second number is increased by 1 , so that it goes like 0, 1, 2, 3, …, 59 . 类似地,每当用户单击“分钟”按钮时,第二个数字就会增加1 ,这样它就类似于0, 1, 2, 3, …, 59 If the minute number is 59 and the user clicks the minute button then the number goes back to 0 . 如果分钟数是59 ,并且用户单击分钟按钮,则该数字将回到0

Here's what I have done so far. 到目前为止,这是我所做的。

<table>
<tr>
<td>
  <button onclick="displaycount()">Hour </button>
</td>
<td>
  <p id="carrier"> 0 </p>
</td>
<td>
  :
</td>
<td>
  <p id="carrier2"> 0 </p>
</td>
<td>
  <button onclick="displaycount2()">Minute </button>
</td>


</tr>
</table>

<script>
var count =(function() {
var counter = 0;
return function() {return counter +=1;}
})();

var count2 =(function() {
var counter = 0;
return function() {return counter +=1;}
})();

function displaycount(){
document.getElementById("carrier").innerHTML = count();
}

function displaycount2(){
document.getElementById("carrier2").innerHTML = count2();
}
</script>

You can use modulus (%) to reset the counter back to 0 for hours and minutes: 您可以使用模数(%)将计数器重置为0小时和数分钟:

 var count = (function() { var counter = 0; return function() { return counter = (counter + 1) % 24; } })(); var count2 = (function() { var counter = 0; return function() { return counter = (counter + 1) % 60; } })(); function displaycount() { document.getElementById("carrier").innerHTML = count(); } function displaycount2() { document.getElementById("carrier2").innerHTML = count2(); } 
 <table> <tr> <td> <button onclick="displaycount()">Hour </button> </td> <td> <p id="carrier"> 0 </p> </td> <td> : </td> <td> <p id="carrier2"> 0 </p> </td> <td> <button onclick="displaycount2()">Minute </button> </td> </tr> </table> 

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

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