首页 > 解决方案 > 单击正确的图像时如何增加计数器

问题描述

我用 HTML 和 Javascript 编写了一个网页,该网页在狮子和青蛙的图像中循环。我设置了 2 个按钮来启动和停止图像每 500 毫秒循环一次。我的问题是我不确定如何创建一个分数函数来计算特定图像被点击的次数。例如,如果点击青蛙图像,我希望得分为 +1,如果点击狮子图像,我希望得分为 -1。这是我的代码。

<html>
  <head>
    <title>Question 2</title>
      <script>
        var images = ["frog.jpg", "lion.jpg"] //I Created an array with both images inside
        var imgInterval;
        var imgi = 'empty';
        var score = document.getElementById('score');
        function start(){
          imgInterval = setInterval(displayImage, 500); //Sets an interval for the func displayImage and for it to loop ever 500ms
        }

        function displayImage() {
          if (imgi == 'empty') { //If the index is empty set the interval to 0 or frog.jpg
          imgi = 0;
        } else if (imgi == 0) { // If the index is set to 0 set it to 1 or lion.jpg
          imgi = 1;
        } else if (imgi == 1) { // If the idex is set to 1 set it back to 0, this creates a loop that will be run every 500ms
          imgi = 0;
        }
          document.getElementById('image').src = images[imgi];
        }

        function stop(){
          clearInterval(imgInterval);
        }

        function scoreNumb() { //This is where i think i am having issues and am unsure what to do.
          if (imgi.onclick == 0) {
            score + 1;
          }
        }
        </script>
  </head>
    <body>
      <button onclick=start()>Start Animation</button>
      <button onclick=stop()>Stop Animation</button>
      <br/> <br/>
      <span>
        <img id="image" onclick=scoreNumb() width="250px" />
      </span>
      <br/>
      <span id="score">0</span>
  </body>
</html>

标签: javascripthtmlarraysonclicksetinterval

解决方案


用我的替换你的函数 scoreNumb

  <script>
    ...
    var score = document.getElementById('score');
    var valueScore = 0; /*created this*/
    ...

    function scoreNumb() { //This is where i think i am having issues and am unsure what to do.
      /*if (imgi.onclick == 0) {
        score + 1;
      }*/
      /*0 = frog AND 1 = lion*/
      if (imgi == 0){/*+1*/
      valueScore++;
      }else {
      valueScore--;
      }
      console.log("click", valueScore);
      document.getElementById('score').textContent = valueScore;
    }

推荐阅读