[英]Display javaScript variable value on HTML page?
我編寫了一個游戲 java 腳本代碼,我需要在 HTML 中顯示分數變量點。 我試過了,但它總是打印 0 而不會增加分數。 Score 變量增加 1,但在 HTML 頁面上它一直顯示 0.我應該在哪里更改標簽以正確顯示它還是我需要更改它的 java 腳本評分函數?
我的 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>
每當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
,因為大小寫中的小錯誤會使識別錯誤變得困難。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.