【问题标题】:Display javaScript variable value on HTML page?在 HTML 页面上显示 javaScript 变量值?
【发布时间】:2020-06-19 21:59:21
【问题描述】:

我编写了一个游戏 java 脚本代码,我需要在 HTML 中显示分数变量点。我试了一下,但它总是打印 0 而不会增加分数。 Score 变量递增 1,但在 HTML 页面上一直显示 0。我应该在哪里更改标签以正确显示它,还是需要更改它的 java script score 函数?

我的 Java 脚本代码:

var notes = [];
var gameStarted = false;
var Score = 0;

// ==== CLASS FOR ARROWS ==== //

// 1. Direction of arrows
// 2. jQuery img that links to direction bottom
// 3. Destroy when it arrow gets to the 
// 4. Explode when arrow gets to the bottom

// Class Arrow
function Arrow(direction) {

    // CSS spacings for the arrows //
    var xPos = null;

    switch(direction) {

        case "left" : xPos = "350px";
        break;

        case "up" : xPos = "420px";
        break;

        case "down" : xPos = "490px";
        break;

        case "right" : xPos = "560px";
        break;

    }

    this.direction = direction;
    this.image = $("<img src='./arrows/" + direction + ".gif'/>");
    this.image.css({

        position: "absolute",
        top: "0px",
        left: xPos

    });

    $('.stage').append(this.image);

}// ends CLASS Arrow

// To enable animating the arrows
Arrow.prototype.step = function() {

    // Controls the speed of the arrows
    this.image.css("top", "+=4px");

};

// Deletes arrows when they get to bottom of page
Arrow.prototype.destroy = function() {

    // removes the image of the DOM
    this.image.remove();

    // Removes the note/arrow from memory/array
    notes.splice(0,1);

};

// Explodes arrow when hit
Arrow.prototype.explode = function() {

    this.image.remove();

};



// For random arrows
var randNum = 0;

// Frame increasing
var frame = 0;

// Determines the speed of notes
var arrowSpawnRate = 40;


// Random generator for arrows
function randomGen() {

    // Randomizes between 1 and 4
    randNum = Math.floor(Math.random() * 4) + 1;

    if (randNum === 1) {

        notes.push(new Arrow("left"));

    }
    if (randNum === 2) {

        notes.push(new Arrow("right"));

    }
    if (randNum === 3) {

        notes.push(new Arrow("up"));

    }
    if (randNum === 4) {

        notes.push(new Arrow("down"));

    }

}// ends randomGen()


// Render function //
function render() {

    if (frame++ % arrowSpawnRate === 0) {

        randomGen();

    }

    // Animate arrows showering down //
    for (var i = notes.length - 1; i >= 0; i--) {

        notes[i].step();

        // Check for cleanup
        if (notes[i].image.position().top > 615) {

            notes[i].destroy();

        }

    }

}// ends render()



// jQuery to animate arrows //
$(document).ready(function () {

    // shim layer with setTimeout fallback
    window.requestAnimFrame = (function() {

         return window.requestAnimationFrame ||

         window.webkitRequestAnimationFrame ||

         window.mozRequestAnimationFrame ||

         function(callback) {

            window.setTimeout(callback, 40 / 75);

        };

    })();

    /*  place the rAF *before* the render() 
        to assure as close to 60fps with the 
        setTimeout fallback.                    */

    // Infinte loop for game play
    (function animloop() {

        if (gameStarted) {

            requestAnimFrame(animloop);

            render();

        } else {

            window.setTimeout(animloop, 1000); // check the state per second

        }

    })();// ends (function animloop() )


});// ends $(doc).ready



// Listening for when the key is pressed
$(document).keydown( function(event) {

    for (var i = 0; i < notes.length; i++) {

            console.log(notes[i].image.position().top);

        if (event.keyCode == 37 && notes[i].direction == "left") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("LEFT! "+notes[i].explode());

                Score++;
            }

        }
        if (event.keyCode == 38 && notes[i].direction == "up") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("UP! "+notes[i].explode());

                Score++;
            }

        }
        if (event.keyCode == 40 && notes[i].direction == "down") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("DOWN! "+notes[i].explode());

                Score++;

            }

        }
        if (event.keyCode == 39 && notes[i].direction == "right") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("RIGHT! "+notes[i].explode());

                Score++;

            }

        }

    }// ends loop

});// ends $(doc).keyup

function score() {
    document.getElementById("Points").innerHTML = Score;
}

HTML 代码:

<html>
<head>
    <link rel="icon" href="./arrows/clubbackground.jpg" type="image/gif" sizes="16x16">
    <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="jsRev.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>DDR-Project 1</title>
</head>
<body>
    <div id="BackgroundScene">
        <div id="DanceScoreboard">
            <div id="GameStopped"><button id="StartBtn" class="btnStyle" onclick="gameStarted=true;">Begin Game</button>
                <br><br><br><div class="Status">Click Begin Game to start</div>
            </div>
            <div id="GameRunning"><button id="StopBtn" class="btnStyle" onclick="gameStarted=false;">Stop Game</button>
                <div id="Status" class="Status"></div>
            </div>
            <div id="dancePoints" class="Points">Points Earned: <div class="OutputText" id="CorrectCount">0</div>
            </div>
        </div>
        <div class="stage"></div> <!-- ENDS .STAGE -->
        <div id="controls">
            <img id="left" src="./arrows/staticLeft.png">
            <img id="up" src="./arrows/staticUp.png">
            <img id="down" src="./arrows/staticDown.png">
            <img id="right" src="./arrows/staticRight.png">
        </div> <!-- ENDS #CONTROLS -->

</body>
</html>

【问题讨论】:

  • @usman khan - 每当您的Score 更新时,请致电score()。在你html 中,没有id 为Points 的元素,而是你有类Points。所以不要使用document.getElementById("Points").innerHTML = Score; 使用document.querySelector(".Points").innerHTML = Score;
  • @random 你能在我的代码中修改它并发布答案吗?
  • @random 我照你说的做了,但一直显示points earned: 0

标签: javascript html


【解决方案1】:

只要Score 变量更新,就调用score 函数。在您的html 中没有id Points 的元素,但是存在class。而不是document.getElementById("Points").innerHTML = Score; 使用document.querySelector(".Points").textContent = Score;。无需使用innerHTML,因为Score 是一个数字而不是html 内容。

var notes = [];
var gameStarted = false;
var Score = 0;

// ==== CLASS FOR ARROWS ==== //

// 1. Direction of arrows
// 2. jQuery img that links to direction bottom
// 3. Destroy when it arrow gets to the 
// 4. Explode when arrow gets to the bottom

// Class Arrow
function Arrow(direction) {
  // CSS spacings for the arrows //
  var xPos = null;

  switch (direction) {
    case "left":
      xPos = "350px";
      break;
    case "up":
      xPos = "420px";
      break;
    case "down":
      xPos = "490px";
      break;
    case "right":
      xPos = "560px";
      break;
  }

  this.direction = direction;
  this.image = $("<img src='./arrows/" + direction + ".gif'/>");
  this.image.css({
    position: "absolute",
    top: "0px",
    left: xPos
  });
  $('.stage').append(this.image);

} // ends CLASS Arrow

// To enable animating the arrows
Arrow.prototype.step = function() {
  // Controls the speed of the arrows
  this.image.css("top", "+=4px");
};

// Deletes arrows when they get to bottom of page
Arrow.prototype.destroy = function() {
  // removes the image of the DOM
  this.image.remove();
  // Removes the note/arrow from memory/array
  notes.splice(0, 1);
};

// Explodes arrow when hit
Arrow.prototype.explode = function() {
  this.image.remove();
};



// For random arrows
var randNum = 0;

// Frame increasing
var frame = 0;

// Determines the speed of notes
var arrowSpawnRate = 40;


// Random generator for arrows
function randomGen() {
  // Randomizes between 1 and 4
  randNum = Math.floor(Math.random() * 4) + 1;
  if (randNum === 1) {
    notes.push(new Arrow("left"));
  }
  if (randNum === 2) {
    notes.push(new Arrow("right"));
  }
  if (randNum === 3) {
    notes.push(new Arrow("up"));
  }
  if (randNum === 4) {
    notes.push(new Arrow("down"));
  }
} // ends randomGen()

// Render function //
function render() {
  if (frame++ % arrowSpawnRate === 0) {
    randomGen();
  }

  // Animate arrows showering down //
  for (var i = notes.length - 1; i >= 0; i--) {
    notes[i].step();
    // Check for cleanup
    if (notes[i].image.position().top > 615) {
      notes[i].destroy();
    }
  }
} // ends render()

// jQuery to animate arrows //
$(document).ready(function() {
  // shim layer with setTimeout fallback
  window.requestAnimFrame = (function() {
    return window.requestAnimationFrame ||
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      function(callback) {
        window.setTimeout(callback, 40 / 75);
      };
  })();

  /*  place the rAF *before* the render() 
      to assure as close to 60fps with the 
      setTimeout fallback.                    */

  // Infinte loop for game play
  (function animloop() {
    if (gameStarted) {
      requestAnimFrame(animloop);
      render();
    } else {
      window.setTimeout(animloop, 1000); // check the state per second
    }
  })(); // ends (function animloop() )
}); // ends $(doc).ready



// Listening for when the key is pressed
$(document).keydown(function(event) {
  for (var i = 0; i < notes.length; i++) {
    if (event.keyCode == 37 && notes[i].direction == "left") {
      if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
        console.log("LEFT! " + notes[i].explode());
        Score++;
        score();
      }
    }
    if (event.keyCode == 38 && notes[i].direction == "up") {
      if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
        console.log("UP! " + notes[i].explode());
        Score++;
        score();
      }
    }
    if (event.keyCode == 40 && notes[i].direction == "down") {
      if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
        console.log("DOWN! " + notes[i].explode());
        Score++;
        score();
      }
    }
    if (event.keyCode == 39 && notes[i].direction == "right") {
      if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {
        console.log("RIGHT! " + notes[i].explode());
        Score++;
        score();
      }
    }
  } // ends loop
}); // ends $(doc).keyup

function score() {
  document.querySelector(".Points").textContent = Score;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="BackgroundScene">
  <div id="DanceScoreboard">
    <div id="GameStopped"><button id="StartBtn" class="btnStyle" onclick="gameStarted=true;">Begin Game</button>
      <br><br><br>
      <div class="Status">Click Begin Game to start</div>
    </div>
    <div id="GameRunning"><button id="StopBtn" class="btnStyle" onclick="gameStarted=false;">Stop Game</button>
      <div id="Status" class="Status"></div>
    </div>
    <div id="dancePoints" class="Points">Points Earned:
      <div class="OutputText" id="CorrectCount">0</div>
    </div>
  </div>
  <div class="stage"></div>
  <!-- ENDS .STAGE -->
  <div id="controls">
    <img id="left" src="./arrows/staticLeft.png">
    <img id="up" src="./arrows/staticUp.png">
    <img id="down" src="./arrows/staticDown.png">
    <img id="right" src="./arrows/staticRight.png">
  </div>
  <!-- ENDS #CONTROLS -->

注意 - 尽可能使用小写的class names 或id names,因为小写错误会导致难以识别错误。

【讨论】:

  • 能否分享整个 HTML 代码?我运行你的代码,但同样它不会增加分数
猜你喜欢
  • 2015-12-28
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 2014-10-24
  • 1970-01-01
相关资源
最近更新 更多