在代码中,我试图在变量自身上添加加号,但我看不到出错的地方:



<!DOCTYPE html>
<html>
  <body>
    <h1>The * Operator</h1>
    <p id="demo"></p>
    <button onclick="myFunction()">Try it</button>

    <script>
      function myFunction() {
        var playerscore = playerscore + 1;
        document.getElementById("demo").innerHTML = playerscore;
      }
    </script>
  </body>
</html>

最佳答案

您需要声明playerscore并将其设置为初始值,在这种情况下可能为0。像这样:



<p id="demo"></p>
<button onclick="myFunction()">Try it</button>
<script>
  var playerscore = 0;

  function myFunction() {
    playerscore = playerscore + 1;
    document.getElementById("demo").innerHTML = playerscore;
  }
</script>

关于javascript - 如何向自身添加变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40586312/

10-09 17:41