当前位置: 首页 > 知识库问答 >
问题:

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

班言
2023-03-14

我写了一个游戏java脚本代码,我需要用超文本标记语言显示分数变量。我尝试它,但它总是打印0,而不是增加分数。分数变量递增1,但在超文本标记语言页面上,它保持显示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>

共有1个答案

禄光霁
2023-03-14

只要更新score变量,就调用score函数。在您的html中没有具有id点的元素,但是存在。而不是文档。getElementById(“点”)。innerHTML=分数 使用文档。查询选择器(“.Points”)。text内容=分数 。无需使用innerHTML,因为分数是一个数字,而不是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 -->

 类似资料:
  • 本文向大家介绍如何在没有document.write的HTML页面中显示JavaScript变量?,包括了如何在没有document.write的HTML页面中显示JavaScript变量?的使用技巧和注意事项,需要的朋友参考一下 在JavaScript中使用Element.innerHTML可以在HTML页面中显示JavaScript变量,而无需document.write。 您可以尝试通过以下

  • 我试图显示与Html文件位于同一文件夹中的静态图像,但似乎无法获得正确显示的正确路径。我正在开发的应用程序还包括一个从数据库获取数据的java后端,我使用HTML和javascript在前端显示它,整个应用程序作为插件在Web服务器上运行。图像和Html文件都位于此处: Web应用程序的URL路径是: <代码>https://staging.com/jira/secure/SchedulerAct

  • 问题内容: 我正在尝试在HTML页面上显示一些JavaScript变量。我第一次使用它,但是当调用该函数时,它用于覆盖当前页面。 在四处搜寻之后,普遍的共识是人们对此不太喜欢。还有哪些其他选择? 我找到了一个建议使用的页面,但该页面写于2005年。 问题答案: 几乎是要走的路。以下是使用它的几种方法: HTML JavaScript 如果您只想更新I 的一部分,通常只需要添加一个类似或类的空元素,

  • 我有这个HTML列表和输入: 这个外部JavaScript代码用于获取我在数组中单击的每个跨度的值 是否有任何可能的方式显示我在输入中单击的跨距??

  • 问题内容: 我正在使用Python制作网络应用程序,并且有一个要在HTML页面上显示的变量。我该怎么做呢?将使用在HTML页面是正确的做法呢? 问题答案: Flask文档中对此进行了非常清楚的解释,因此建议您阅读此书以全面理解,但这是呈现模板变量的非常简单的示例。 HTML模板文件存储在: 和简单的Flask应用程序: 运行此脚本,然后在浏览器中访问http://127.0.0.1:5000/。您

  • 问题内容: 我正在为网络相册应用程序创建一套Selenium测试。我想测试图像是否实际显示(它包含有效的图像数据)。这样的事情可能吗? 问题答案: 在图像的src符合预期但图像未显示在页面上之前,我遇到过类似的情况。 您可以使用JavaScriptExcecutor检查图像是否显示。 使用以下代码-传递WebElement(图像)- 通过执行此操作,可以验证图像是否已实际加载到网页上。