4次后自动重置计数器

我建立了一个计数器,但如果值 = 4,我无法自动重置计数器


<!DOCTYPE html>

<html>

<body>


<span class="hits"> 0 </span>

<button onclick="resetHits()" class="tryagain">RESTART</button>


<script>

var hits = 0;

var hitElement = document.querySelector('.hits');

document.body.onkeyup = function(e) {

if(e.keyCode == 32) {addHit()}}

var addHit = function() {hits++; renderHits()}

var renderHits = function() {hitElement.innerHTML = hits}

var resetHits = function() {hits = 0; renderHits()}

</script>

</body>

</html>  


繁星coding
浏览 104回答 3
3回答

蛊毒传说

hitElement.innerHTML = hits % 5var hits = 0;var hitElement = document.querySelector(".hits");document.body.onkeyup = function (e) {&nbsp; if (e.keyCode == 32) {&nbsp; &nbsp; addHit();&nbsp; }};var addHit = function () {&nbsp; hits++;&nbsp; renderHits();};var renderHits = function () {&nbsp; hitElement.innerHTML = hits %= 5;&nbsp; console.log({hits});};var resetHits = function () {&nbsp; hits = 0;&nbsp; renderHits();};<span class="hits"> 0 </span><button onclick="resetHits()" class="tryagain">RESTART</button>更新:根据@tarkh 的观点,更新为hitElement.innerHTML = hits %= 5;,因此该变量值也是最新的。

ABOUTYOU

在这里我修改你的代码<!DOCTYPE html><html><body><span class="hits"> 0 </span><button onclick="resetHits()" class="tryagain">RESTART</button><script>var hits = 0;var hitElement = document.querySelector('.hits');document.body.onkeyup = function(e) {&nbsp; if(e.keyCode == 32) {&nbsp; &nbsp; // ADD counter check here&nbsp; &nbsp; if(hits === 4 + 1) { // Add +1 if you need do reset after 4 displayed&nbsp; &nbsp; &nbsp; // Do what you want&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; resetHits();&nbsp; &nbsp; }&nbsp; &nbsp; // Then it depends on your logic,&nbsp; &nbsp; // if you don't need to cycle counter immediately,&nbsp; &nbsp; // add rest to else condition like so&nbsp; &nbsp; else { addHit(); }&nbsp; }}var addHit = function() {hits++; renderHits()}var renderHits = function() {hitElement.innerHTML = hits}var resetHits = function() {hits = 0; renderHits()}</script></body></html>

小怪兽爱吃肉

试试这个。4 不会显示。它将自动重置为 0。<!DOCTYPE html><html><body><span class="hits"> 0 </span><button onclick="resetHits()" class="tryagain">RESTART</button><script>var hits = 0;var hitElement = document.querySelector('.hits');document.body.onkeyup = function(e) {if(e.keyCode == 32) {addHit()}}var addHit = function() {&nbsp; &nbsp;hits++;&nbsp;&nbsp; &nbsp;if (hits === 4) {&nbsp; &nbsp; &nbsp;resetHits();&nbsp; &nbsp;}&nbsp; &nbsp;renderHits()}var renderHits = function() {hitElement.innerHTML = hits}var resetHits = function() {hits = 0; renderHits()}</script></body></html>&nbsp;&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript