If 语句不适用于空格键计数

所以我建立了一个计数器,但我没有设法实现 if 语句。


前任:


if (hits == 1) {alert("hello world1")}

if (hits == 2) {alert("hello world2")}

if (hits == 3) {alert("hello world3")}

if (hits == 4) {alert("hello world4")}

这是我的代码


    <html>

    <body>


    <p id="hits" value="0"> </p>


    <script>

      var hits = 0;

      var hitElement = document.getElementById("hits");

      document.body.onkeyup = function(e) {

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

      }

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

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

      var resetHits = function() {renderHits()}

    </script>


    </body>

    </html>

另外我想知道是否有可能让它基于 .value 而不是 .innerHTML 工作(因为我的目标是空间计数器在“幕后”工作,所以它不应该是可见的)。


慕勒3428872
浏览 124回答 3
3回答

慕容3067478

实际上我的目标是按输入栏在图像之间切换let hits = 0;const hitElement = document.getElementById("hits");const images = [&nbsp; &nbsp; "https://via.placeholder.com/50x50.png?text=qwe", // your 1 image&nbsp; &nbsp; "https://via.placeholder.com/50x50.png?text=rty", // your 2 image&nbsp; &nbsp; "https://via.placeholder.com/50x50.png?text=uyi", // your 3 image&nbsp; &nbsp; "https://via.placeholder.com/50x50.png?text=opd", // your 4 image&nbsp; &nbsp; "https://via.placeholder.com/50x50.png?text=asd", // your 5 image];document.body.onkeyup = function (e) {&nbsp; &nbsp; if (e.keyCode === 32) {&nbsp; &nbsp; &nbsp; &nbsp; hits++;&nbsp; &nbsp; &nbsp; &nbsp; hitElement.src = images[hits % images.length];&nbsp; &nbsp; }};<p>Press spacebar</p><img id="hits" src="https://via.placeholder.com/50x50.png?text=qwe" />

哔哔one

&nbsp; &nbsp; <body>&nbsp; &nbsp; <h1>HELLO WORLD</h1>&nbsp; &nbsp; <p id="hits" value="0"> 0</p>&nbsp;<script>&nbsp;var hits = 0;&nbsp;var hitElement = document.getElementById("hits");&nbsp;document.body.onkeyup = function(e) {&nbsp;if (e.keyCode == 32) {addHit()}}&nbsp;var addHit = function() {hits++; renderHits()}&nbsp;var renderHits = function() {hitElement.innerText = hits % 5}&nbsp; var resetHits = function() {renderHits()}

慕尼黑8549860

它是“点击率 % 5”的东西。解释器将其视为 ((lresult = a) % b) 而不是 (lresult=(a % b))。需要括号。let hits = 0;const hitElement = document.getElementById("hits");document.body.onkeyup = function (e) {&nbsp; &nbsp; if (e.keyCode === 32) {&nbsp; &nbsp; &nbsp; &nbsp; hits++;&nbsp; &nbsp; &nbsp; &nbsp; hitElement.src = `https://via.placeholder.com/50x50.png?text=${(hits % 5)&nbsp; + 1}`;&nbsp; &nbsp; }};<p>Press spacebar</p><img id="hits" src="https://via.placeholder.com/50x50.png?text=1"></ing>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript