首页 > 解决方案 > 如何在值更改时更新 javascript 变量?

问题描述

我的代码通过这段代码计算用户得分

context.fillText('Score: ' + (current - 1).toString(), 20, 40);

我将其转移(current - 1)到一个变量中,并使用以下代码显示它是一个标题

<script>
  var number = (current - 1).toString()

  function docWrite(variable) {
    document.write(variable);
  }
</script>

<h1>the value for number is: <script>docWrite(number)</script></h1>

现在,每次我的总分更新时,我都无法更新变量,因为它保持在“0”。如果我的“有经验的前辈”能指出我的(可能)愚蠢的错误,我将不胜感激。

这是我的代码的完整概述

<html>

<body>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    * {
      box-sizing: border-box
    }
    
    /* Set height of body and the document to 100% */
    body,
    html {
      height: 100%;
      margin: 0;
      font-family: adventure;
    }
    
    /* Style tab links */
    .tablink {
      background-color: #111;
      color: Yellow;
      float: left;
      border: none;
      outline: none;
      cursor: pointer;
      padding: 14px 16px;
      font-size: 17px;
      width: 25%;
    }
    
    .tablink:hover {
      background-color: #999;
    }
    
    /* Style the tab content (and add height:100% for full page content) */
    .tabcontent {
      color: black;
      display: none;
      padding: 100px 20px;
      height: 100%;
    }
    
    p5 {
      width: 20%;
      height: 10%;
      position: absolute;
      top: 800px;
      right: 300px;
      font-family: Arial;
      text-align: center;
      font-size: 30px;
      color: white;
      border: none;
      outline: none;
    }
    
    #Home {
      background-color: red;
    }
    
    #Game {
      background-color: green;
    }
    
    #Contact {
      background-color: blue;
    }
    
    #About {
      background-color: Yellow;
    }
  </style>

  <button4 class="tablink" onclick="openPage('Home', this, 'red')" style="">Home</button4>
  <button4 class="tablink" onclick="openPage('Game', this, 'green')" id="defaultOpen" style="background-color: green;">Game</button4>
  <button4 class="tablink" onclick="openPage('Contact', this, 'blue')" style="">Contact</button4>
  <button4 class="tablink" onclick="openPage('About', this, 'yellow')" style="">About</button4>

  <div id="Home" class="tabcontent" style="display: block;">
    <h1>Home</h1>
    <p>Home is where the heart is..</p>
  </div>

  <div id="Contact" class="tabcontent" style="display: none;">
    <h1>Contact</h1>
    <p>Get in touch, or swing by for a cup of coffee.</p>
  </div>

  <div id="About" class="tabcontent" style="display: none;">
    <h1>About</h1>
    <p>Who we are and what we do.</p>
  </div>

  <div id="Game" class="tabcontent" style="display: none;">
    <div id="Game" class="tabcontent" style="display: block;">
      <h1>Game</h1>
      <p>Some Game this fine day!</p>
    </div>

    <script>
      function openPage(pageName, elmnt, color) {
        var i, tabcontent, tablinks;

        tabcontent = document.getElementsByClassName("tabcontent");
        for (i = 0; i < tabcontent.length; i++) {
          tabcontent[i].style.display = "none";
        }

        tablinks = document.getElementsByClassName("tablink");
        for (i = 0; i < tablinks.length; i++) {
          tablinks[i].style.backgroundColor = "";
        }

        document.getElementById(pageName).style.display = "block";
        elmnt.style.backgroundColor = color;
      }
      // Get the element with id="defaultOpen" and click on it
      document.getElementById("defaultOpen").click();
    </script>

    <canvas id="myCanvas" width="800" height="500" style="border:80px solid #ffffff;"></canvas>
    <style>
      body {
        background-image: url('help.jpg');
        background-repeat: no-repeat;
        background-attachment: fixed;
        background-size: cover;
      }
    </style>

    <p style="width: 300px; vertical-align:top"></p>
    <p1 id="message001">What is <text id="name001">10/2</text>?</p1>

    <div id="disappear001"><input type="text" id="input001" autofocus=""></div>
    <div id="disappear002"><button onclick="submit001()">Submit</button></div>

    <p id="answer001"></p>
    <p3 id="button001"></p3>
    <p3 id="button002"></p3>

    <style>
      input {
        top: 400px;
        right: 330px;
        width: 18%;
        height: 6%;
        position: absolute;
      }
      
      button {
        width: 10%;
        height: 6%;
        position: absolute;
        font-family: Arial;
        top: 400px;
        right: 120px;
        text-align: center;
        font-size: 25px;
        color: white;
        border: none;
        outline: none;
        cursor: pointer;
        border-radius: 5px;
        background-color: #000208;
      }
      
      button:hover {
        transition: 0.05s;
        background-color: #0B4870;
        transform: rotateZ(-5deg);
        box-shadow: 0 0 30px -10px #0B4870;
      }
      
      button:active {
        transform: translateY(20px);
        transform: rotateZ(5deg);
      }
      
      button2 {
        width: 5%;
        height: 6%;
        position: absolute;
        font-family: Arial;
        top: 400px;
        right: 300px;
        text-align: center;
        font-size: 40px;
        color: white;
        border: none;
        outline: none;
        cursor: pointer;
        border-radius: 5px;
        background-color: #000208;
      }
      
      button:hover {
        transition: 0.05s;
        background-color: #0B4870;
        transform: rotateZ(-5deg);
        box-shadow: 0 0 30px -10px #0B4870;
      }
      
      button:active {
        transform: translateY(20px);
        transform: rotateZ(5deg);
      }
      
      p1 {
        width: 30%;
        height: 10%;
        position: absolute;
        top: 300px;
        right: 110px;
        font-family: Arial;
        text-align: center;
        font-size: 60px;
        color: white;
        border: none;
        outline: none;
        border-radius: 5px;
        background-color: #000208;
      }
      
      p {
        width: 20%;
        height: 10%;
        position: absolute;
        top: 450px;
        right: 300px;
        font-family: Arial;
        text-align: center;
        font-size: 30px;
        color: white;
        border: none;
        outline: none;
      }
    </style>

    <script type="text/javascript">
      var question001 = ["6-8", "10/2", "3+7", "5-3", "18+12"];
      var answer001 = ["-2", "5", "10", "2", "30"];
      var random001 = Math.floor(Math.random() * question001.length);

      function submit001() {
        var b = input001.value;

        if (random001 == 0 && b == answer001[0]) {
          document.getElementById("answer001").innerHTML = "Correct..";
          document.getElementById("button001").innerHTML = "<button onclick=btn001()>Next</button>";
          document.getElementById("disappear002").innerHTML = "";
        } else if (random001 == 1 && b == answer001[1]) {
          document.getElementById("answer001").innerHTML = "Correct..";
          document.getElementById("button001").innerHTML = "<button onclick=btn001()>Next</button>";
          document.getElementById("disappear002").innerHTML = "";
        } else if (random001 == 2 && b == answer001[2]) {
          document.getElementById("answer001").innerHTML = "Correct..";
          document.getElementById("button001").innerHTML = "<button onclick=btn001()>Next</button>";
          document.getElementById("disappear002").innerHTML = "";
        } else if (random001 == 3 && b == answer001[3]) {
          document.getElementById("answer001").innerHTML = "Correct..";
          document.getElementById("button001").innerHTML = "<button onclick=btn001()>Next</button>";
          document.getElementById("disappear002").innerHTML = "";
        } else if (random001 == 4 && b == answer001[4]) {
          document.getElementById("answer001").innerHTML = "Correct..";
          document.getElementById("button001").innerHTML = "<button onclick=btn001()>Next</button>";
          document.getElementById("disappear002").innerHTML = "";
        } else {
          document.getElementById("answer001").innerHTML = "Game Over";
          document.getElementById("button002").innerHTML = "<button onclick=window.location.reload()>Reset</button>";
          document.getElementById("disappear002").innerHTML = "";
          gameOver();
        }
      }

      document.getElementById("name001").innerHTML = question001[random001];

      function btn001() {
        random001 = Math.floor(Math.random() * question001.length);
        document.getElementById("name001").innerHTML = question001[random001];
        document.getElementById("button001").innerHTML = "";
        document.getElementById("disappear001").innerHTML = "<input type=text id=input001 autofocus>";
        document.getElementById("disappear002").innerHTML = "<button onclick=submit001()>Submit</button>";
        document.getElementById("answer001").innerHTML = "";
      }

      function question() {
        return document.getElementById("message001").textContent;
      }

      let canvas = document.getElementById("myCanvas");
      let context = canvas.getContext("2d");
      context.font = '30px arial';
      let scrollCounter, cameraY, current, mode;
      let ySpeed = 5;
      let height = 50;
      let boxes = [];

      boxes[0] = {
        x: 300,
        y: 200,
        width: 200
      };
      let debris = {
        x: 300,
        width: 0
      };

      function newBox() {
        boxes[current] = {
          x: 300,
          y: (current + 10) * height,
          width: boxes[current - 1].width
        };
      }

      function gameOver() {
        mode = 'gameOver';
        context.fillText('Your tower collapsed! Wanna play again?', 200, 40);
      }

      function animate() {
        if (mode != 'gameOver') {
          context.clearRect(0, 0, canvas.width, canvas.height);
          context.fillText('Score: ' + (current - 1).toString(), 20, 40);
          for (let n = 0; n < boxes.length; n++) {
            let box = boxes[n];
            context.fillStyle = 'rgb(' + n * 14 + ',' + n * 23 + ',' + n * 25 + ')';
            context.fillRect(box.x, 600 - box.y + cameraY, box.width, height);

          }
          context.fillStyle = 'white';
          context.fillText(question(), 310, 440);
          context.fillRect(debris.x, 600 - debris.y + cameraY, debris.width, height);
          if (mode == 'bounce') {
            boxes[current].x = boxes[current].x + xSpeed;
            if (xSpeed > 0 && boxes[current].x + boxes[current].width > canvas.width)
              xSpeed = -xSpeed;
            if (xSpeed < 0 && boxes[current].x < 0)
              xSpeed = -xSpeed;
          }
          if (mode == 'fall') {
            boxes[current].y = boxes[current].y - ySpeed;
            if (boxes[current].y == boxes[current - 1].y + height) {
              mode = 'bounce';
              let difference = boxes[current].x - boxes[current - 1].x;
              if (Math.abs(difference) >= boxes[current].width) {
                gameOver();
              }
              debris = {
                y: boxes[current].y,
                width: difference
              };
              if (boxes[current].x > boxes[current - 1].x) {
                boxes[current].width = boxes[current].width - difference;
                debris.x = boxes[current].x + boxes[current].width;
              } else {
                debris.x = boxes[current].x - difference;
                boxes[current].width = boxes[current].width + difference;
                boxes[current].x = boxes[current - 1].x;
              }

              current++;
              scrollCounter = height;
              newBox();
            }
          }
          debris.y = debris.y - ySpeed;
          if (scrollCounter) {
            cameraY++;
            scrollCounter--;
          }
        }
        window.requestAnimationFrame(animate);
      }

      function restart() {
        boxes.splice(1, boxes.length - 1);
        mode = 'bounce';
        cameraY = 0;
        scrollCounter = 0;
        xSpeed = 0;
        current = 1;
        newBox();
        debris.y = 0;
      }

      document.getElementById("disappear002").onclick = function() {
        if (mode == 'gameOver')
          restart();
        else {
          if (mode == 'bounce')
            mode = 'fall';
        }
      };

      restart();
      animate();
    </script>

    <div class="as-console-wrapper"></div>
    <div class="as-console"></div>

    <script>
      var number = (current - 1).toString()

      function docWrite(variable) {
        document.write(variable);
      }
    </script>

    <h1>Total Score:
      <script>
        docWrite(number)
      </script>
    </h1>

</body>

</html>

标签: javascripthtml

解决方案


我认为Total score应该在游戏结束后更新。因此,您应该在函数中输出分数gameOver()。如果您想在每次提交时更新它,您必须将逻辑添加到函数animate()中。

逻辑很简单:

  • 获取Total score元素:
let total_score = document.querySelector('#total-score');
  • 并将当前分数添加到其内容中(您必须将其转换为parseInt()之前的整数):
total_score.innerHTML = parseInt(total_score.innerHTML) + current - 1;

工作示例:

我将所有 js-code 和所有 css-code 合并到一个 js-分别为 css-block 以提高堆栈片段的可读性和适当的使用。

function openPage(pageName, elmnt, color) {
  var i, tabcontent, tablinks;

  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }

  tablinks = document.getElementsByClassName("tablink");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].style.backgroundColor = "";
  }

  document.getElementById(pageName).style.display = "block";
  elmnt.style.backgroundColor = color;
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();

var question001 = ["6-8", "10/2", "3+7", "5-3", "18+12"];
var answer001 = ["-2", "5", "10", "2", "30"];
var random001 = Math.floor(Math.random() * question001.length);

function submit001() {
  var b = input001.value;

  if (random001 == 0 && b == answer001[0]) {
    document.getElementById("answer001").innerHTML = "Correct..";
    document.getElementById("button001").innerHTML = "<button onclick=btn001()>Next</button>";
    document.getElementById("disappear002").innerHTML = "";
  } else if (random001 == 1 && b == answer001[1]) {
    document.getElementById("answer001").innerHTML = "Correct..";
    document.getElementById("button001").innerHTML = "<button onclick=btn001()>Next</button>";
    document.getElementById("disappear002").innerHTML = "";
  } else if (random001 == 2 && b == answer001[2]) {
    document.getElementById("answer001").innerHTML = "Correct..";
    document.getElementById("button001").innerHTML = "<button onclick=btn001()>Next</button>";
    document.getElementById("disappear002").innerHTML = "";
  } else if (random001 == 3 && b == answer001[3]) {
    document.getElementById("answer001").innerHTML = "Correct..";
    document.getElementById("button001").innerHTML = "<button onclick=btn001()>Next</button>";
    document.getElementById("disappear002").innerHTML = "";
  } else if (random001 == 4 && b == answer001[4]) {
    document.getElementById("answer001").innerHTML = "Correct..";
    document.getElementById("button001").innerHTML = "<button onclick=btn001()>Next</button>";
    document.getElementById("disappear002").innerHTML = "";
  } else {
    document.getElementById("answer001").innerHTML = "Game Over";
    document.getElementById("button002").innerHTML = "<button onclick=window.location.reload()>Reset</button>";
    document.getElementById("disappear002").innerHTML = "";
    gameOver();
  }
}

document.getElementById("name001").innerHTML = question001[random001];

function btn001() {
  random001 = Math.floor(Math.random() * question001.length);
  document.getElementById("name001").innerHTML = question001[random001];
  document.getElementById("button001").innerHTML = "";
  document.getElementById("disappear001").innerHTML = "<input type=text id=input001 autofocus>";
  document.getElementById("disappear002").innerHTML = "<button onclick=submit001()>Submit</button>";
  document.getElementById("answer001").innerHTML = "";
}

function question() {
  return document.getElementById("message001").textContent;
}

let canvas = document.getElementById("myCanvas");
let context = canvas.getContext("2d");
context.font = '30px arial';
let scrollCounter, cameraY, current, mode;
let total_score = document.querySelector('#total-score');
let ySpeed = 5;
let height = 50;
let boxes = [];

boxes[0] = {
  x: 300,
  y: 200,
  width: 200
};
let debris = {
  x: 300,
  width: 0
};

function newBox() {
  boxes[current] = {
    x: 300,
    y: (current + 10) * height,
    width: boxes[current - 1].width
  };
}

function gameOver() {
  mode = 'gameOver';
  context.fillText('Your tower collapsed! Wanna play again?', 200, 40);
  total_score.innerHTML = parseInt(total_score.innerHTML) + current - 1;
}

function animate() {
  if (mode != 'gameOver') {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.fillText('Score: ' + (current - 1).toString(), 20, 40);
    for (let n = 0; n < boxes.length; n++) {
      let box = boxes[n];
      context.fillStyle = 'rgb(' + n * 14 + ',' + n * 23 + ',' + n * 25 + ')';
      context.fillRect(box.x, 600 - box.y + cameraY, box.width, height);

    }
    context.fillStyle = 'white';
    context.fillText(question(), 310, 440);
    context.fillRect(debris.x, 600 - debris.y + cameraY, debris.width, height);
    if (mode == 'bounce') {
      boxes[current].x = boxes[current].x + xSpeed;
      if (xSpeed > 0 && boxes[current].x + boxes[current].width > canvas.width)
        xSpeed = -xSpeed;
      if (xSpeed < 0 && boxes[current].x < 0)
        xSpeed = -xSpeed;
    }
    if (mode == 'fall') {
      boxes[current].y = boxes[current].y - ySpeed;
      if (boxes[current].y == boxes[current - 1].y + height) {
        mode = 'bounce';
        let difference = boxes[current].x - boxes[current - 1].x;
        if (Math.abs(difference) >= boxes[current].width) {
          gameOver();
        }
        debris = {
          y: boxes[current].y,
          width: difference
        };
        if (boxes[current].x > boxes[current - 1].x) {
          boxes[current].width = boxes[current].width - difference;
          debris.x = boxes[current].x + boxes[current].width;
        } else {
          debris.x = boxes[current].x - difference;
          boxes[current].width = boxes[current].width + difference;
          boxes[current].x = boxes[current - 1].x;
        }

        current++;
        scrollCounter = height;
        newBox();
      }
    }
    debris.y = debris.y - ySpeed;
    if (scrollCounter) {
      cameraY++;
      scrollCounter--;
    }
  }
  window.requestAnimationFrame(animate);
}

function restart() {
  boxes.splice(1, boxes.length - 1);
  mode = 'bounce';
  cameraY = 0;
  scrollCounter = 0;
  xSpeed = 0;
  current = 1;
  newBox();
  debris.y = 0;
}

document.getElementById("disappear002").onclick = function() {
  if (mode == 'gameOver')
    restart();
  else {
    if (mode == 'bounce')
      mode = 'fall';
  }
};

restart();
animate();
* {
  box-sizing: border-box
}

/* Set height of body and the document to 100% */
body,
html {
  height: 100%;
  margin: 0;
  font-family: adventure;
}

/* Style tab links */
.tablink {
  background-color: #111;
  color: Yellow;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  font-size: 17px;
  width: 25%;
}

.tablink:hover {
  background-color: #999;
}

/* Style the tab content (and add height:100% for full page content) */
.tabcontent {
  color: black;
  display: none;
  padding: 100px 20px;
  height: 100%;
}

p5 {
  width: 20%;
  height: 10%;
  position: absolute;
  top: 800px;
  right: 300px;
  font-family: Arial;
  text-align: center;
  font-size: 30px;
  color: white;
  border: none;
  outline: none;
}

#Home {
  background-color: red;
}

#Game {
  background-color: green;
}

#Contact {
  background-color: blue;
}

#About {
  background-color: Yellow;
}

body {
  background-image: url('help.jpg');
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
}

input {
  top: 400px;
  right: 330px;
  width: 18%;
  height: 6%;
  position: absolute;
}

button {
  width: 10%;
  height: 6%;
  position: absolute;
  font-family: Arial;
  top: 400px;
  right: 120px;
  text-align: center;
  font-size: 25px;
  color: white;
  border: none;
  outline: none;
  cursor: pointer;
  border-radius: 5px;
  background-color: #000208;
}

button:hover {
  transition: 0.05s;
  background-color: #0B4870;
  transform: rotateZ(-5deg);
  box-shadow: 0 0 30px -10px #0B4870;
}

button:active {
  transform: translateY(20px);
  transform: rotateZ(5deg);
}

button2 {
  width: 5%;
  height: 6%;
  position: absolute;
  font-family: Arial;
  top: 400px;
  right: 300px;
  text-align: center;
  font-size: 40px;
  color: white;
  border: none;
  outline: none;
  cursor: pointer;
  border-radius: 5px;
  background-color: #000208;
}

button:hover {
  transition: 0.05s;
  background-color: #0B4870;
  transform: rotateZ(-5deg);
  box-shadow: 0 0 30px -10px #0B4870;
}

button:active {
  transform: translateY(20px);
  transform: rotateZ(5deg);
}

p1 {
  width: 30%;
  height: 10%;
  position: absolute;
  top: 300px;
  right: 110px;
  font-family: Arial;
  text-align: center;
  font-size: 60px;
  color: white;
  border: none;
  outline: none;
  border-radius: 5px;
  background-color: #000208;
}

p {
  width: 20%;
  height: 10%;
  position: absolute;
  top: 450px;
  right: 300px;
  font-family: Arial;
  text-align: center;
  font-size: 30px;
  color: white;
  border: none;
  outline: none;
}
<button4 class="tablink" onclick="openPage('Home', this, 'red')" style="">Home</button4>
<button4 class="tablink" onclick="openPage('Game', this, 'green')" id="defaultOpen" style="background-color: green;">Game</button4>
<button4 class="tablink" onclick="openPage('Contact', this, 'blue')" style="">Contact</button4>
<button4 class="tablink" onclick="openPage('About', this, 'yellow')" style="">About</button4>

<div id="Home" class="tabcontent" style="display: block;">
  <h1>Home</h1>
  <p>Home is where the heart is..</p>
</div>

<div id="Contact" class="tabcontent" style="display: none;">
  <h1>Contact</h1>
  <p>Get in touch, or swing by for a cup of coffee.</p>
</div>

<div id="About" class="tabcontent" style="display: none;">
  <h1>About</h1>
  <p>Who we are and what we do.</p>
</div>

<div id="Game" class="tabcontent" style="display: none;">
  <div id="Game" class="tabcontent" style="display: block;">
    <h1>Game</h1>
    <p>Some Game this fine day!</p>
  </div>

  <canvas id="myCanvas" width="800" height="500" style="border:80px solid #ffffff;"></canvas>

  <p style="width: 300px; vertical-align:top"></p>
  <p1 id="message001">What is <text id="name001">10/2</text>?</p1>

  <div id="disappear001"><input type="text" id="input001" autofocus=""></div>
  <div id="disappear002"><button onclick="submit001()">Submit</button></div>

  <p id="answer001"></p>
  <p3 id="button001"></p3>
  <p3 id="button002"></p3>

  <div class="as-console-wrapper"></div>
  <div class="as-console"></div>

  <h1>Total Score: <span id="total-score">0</span></h1>


推荐阅读