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

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

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

慕勒3428872 2022-12-22 12:48:11
所以我建立了一个计数器,但我没有设法实现 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 工作(因为我的目标是空间计数器在“幕后”工作,所以它不应该是可见的)。
查看完整描述

3 回答

?
慕容3067478

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

实际上我的目标是按输入栏在图像之间切换


let hits = 0;

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


const images = [

    "https://via.placeholder.com/50x50.png?text=qwe", // your 1 image

    "https://via.placeholder.com/50x50.png?text=rty", // your 2 image

    "https://via.placeholder.com/50x50.png?text=uyi", // your 3 image

    "https://via.placeholder.com/50x50.png?text=opd", // your 4 image

    "https://via.placeholder.com/50x50.png?text=asd", // your 5 image

];


document.body.onkeyup = function (e) {

    if (e.keyCode === 32) {

        hits++;

        hitElement.src = images[hits % images.length];

    }

};

<p>Press spacebar</p>

<img id="hits" src="https://via.placeholder.com/50x50.png?text=qwe" />


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

TA贡献1854条经验 获得超8个赞

    <body>

    <h1>HELLO WORLD</h1>

    <p id="hits" value="0"> 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.innerText = hits % 5}

  var resetHits = function() {renderHits()}


查看完整回答
反对 回复 2022-12-22
?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

它是“点击率 % 5”的东西。解释器将其视为 ((lresult = a) % b) 而不是 (lresult=(a % b))。


需要括号。


let hits = 0;

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


document.body.onkeyup = function (e) {

    if (e.keyCode === 32) {

        hits++;

        hitElement.src = `https://via.placeholder.com/50x50.png?text=${(hits % 5)  + 1}`;

    }

};

<p>Press spacebar</p>

<img id="hits" src="https://via.placeholder.com/50x50.png?text=1"></ing>


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

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号