繁体   English   中英

在 HTML 页面上显示 javaScript 变量值?

[英]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 namesid names ,因为大小写中的小错误会使识别错误变得困难。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM