我无法使用Javascript从HTML中获取元素

问题描述 投票:-5回答:1

我想用颜色创建一个项目。

我的所有文件都在同一个文件夹中。

我无法通过以下方式访问index.html中的颜色输入:

const firstColor = document.getElementById("color1").value;

我可以到达game.js中的元素。

我的画布也在game.html中。

我在所有HTML文件中添加了标签。

我的index.html:

    <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Cyber Bird</title>
  <link rel="stylesheet" href="main.css">
</head>
<body align="center">
  <div id="title">Cyber Bird</div>
  <div id="mainMenu">
    <div id="selectColors">
      <div id="colorsTitle">SELECT <span>2</span> COLORS FOR YOUR <span id="cb">CYBER BIRD</span></div> <br> <hr> <br>
      <span id="first"> First: <input type="color" name="color1" id="color1" value="#f1aabc"></span>
    <span id="second"> Second: <input type="color" name="color2" id="color2" value="#2d96b9"></span>
    </div>
    <a href="game.html" class="button" id="startCyber">START</a>
  </div>
  <script src="src/game.js"></script>
</body>
</html>

我的game.html:

      <!DOCTYPE html>
  <html>
  <head>
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <title>Cyber Bird</title>
     <link rel="stylesheet" href="main.css">
  </head>
  <body>
     <div id="container" align="center">
        <div id="scoreBoard">
           <div id="header">SCOREBOARD</div>
           <div id="description">Score: </div>
           <div id="score">0</div>
        </div>

        <canvas id="myCanvas" height="500" width="900"></canvas>
        <div class="helper" id="toJump">press <span>SPACE</span> to jump</div>
        <div class="helper" id="toStart">click <span onclick="startGame()">HERE</span> to start</div>
        <div class="helper" id="toSelect">select new <span><a href="index.html">COLORS</a></span></div>
     </div>
     <div id="darken"></div>
     <div id="gameOver" align="center">
           <div id="message">GAME OVER</div>
           <div id="yourScore">Your score is: <span id="finalScore"></span></div>
           <div id="tryAgain" class="button" onclick="startGame()">Try Again</div>
     </div>
     <script src="game.js"></script>
  </body>
  </html>
javascript getelementbyid
1个回答
0
投票

您没有将数据从index.html传递到game.html。所以当你这样称呼时:

<a href="game.html" class="button" id="startCyber">START</a>

您正在加载新页面,该页面会删除所有现有变量 - 包括“color1”。

我在这里看到2个选项:

  1. 使这个单页Web应用程序。因此,当您单击START按钮时,它会隐藏索引div并加载游戏div
  2. 从index.html某处保存您的值(浏览器存储?),然后在加载新的game.html页面后调用它。
© www.soinside.com 2019 - 2024. All rights reserved.