为了账号安全,请及时绑定邮箱和手机立即绑定

4次后自动重置计数器

4次后自动重置计数器

繁星coding 2022-12-22 12:02:10
我建立了一个计数器,但如果值 = 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>  
查看完整描述

3 回答

?
蛊毒传说

TA贡献1895条经验 获得超3个赞

hitElement.innerHTML = hits % 5


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 %= 5;

  console.log({hits});

};

var resetHits = function () {

  hits = 0;

  renderHits();

};

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

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

更新:根据@tarkh 的观点,更新为hitElement.innerHTML = hits %= 5;,因此该变量值也是最新的。



查看完整回答
反对 回复 2022-12-22
?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

在这里我修改你的代码


<!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) {

    // ADD counter check here

    if(hits === 4 + 1) { // Add +1 if you need do reset after 4 displayed

      // Do what you want  

      resetHits();

    }

    // Then it depends on your logic,

    // if you don't need to cycle counter immediately,

    // add rest to else condition like so

    else { addHit(); }

  }

}

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

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

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

</script>

</body>

</html>


查看完整回答
反对 回复 2022-12-22
?
小怪兽爱吃肉

TA贡献1852条经验 获得超1个赞

试试这个。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() {

   hits++; 

   if (hits === 4) {

     resetHits();

   }

   renderHits()

}

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

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

</script>

</body>

</html>  


查看完整回答
反对 回复 2022-12-22
  • 3 回答
  • 0 关注
  • 103 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信