在onload函数中访问DOM元素

问题描述 投票:0回答:1

[嘿,我想构建这个计算器,它应该在页面加载时生成随机数并将其描述在DOM中。现在,我收到此错误消息:“无法分配给函数调用”。有人可以帮我解决这个问题。预先感谢。

let add1;
let add2;

function displayNewEquation() {
  add1 = Math.floor(Math.random() * 500);
  add2 = Math.floor(Math.random() * 500);
  document.getElementsByTagName("equation") = `<p> ${add1} + ${add2} = </p>`;
}

window.onload = () => {
  displayNewEquation();
};

function checkEquation() {
  var input = parseInt(document.getElementById("solution").value);
  console.log(input);
  if (input == add1 + add2) {
    displayNewEquation();
  } else {
    var inputfield = document.getElementById("solution");
    inputfield.style.borderColor = "crimson";
  }
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>mathle</title>
    <link rel="stylesheet" href="Style/Addition.css" />
    <script type="text/javascript" src="./Logic/Addition.js"></script>
  </head>
  <body>
    <div class="additionIntro">
      <p class="title">
        - Addition -
      </p>
      <button class="back" onclick="goHome()">Back</button>
    </div>
    <div class="additionMain">
      <div class="calculation">
        <p class="equation">9 + 13 =</p>
        <input id="solution" type="number" oninput="checkEquation()" />
      </div>
    </div>
  </body>
</html>
javascript html dom calculator onload
1个回答
1
投票

正如@Patrick Evans所评论的那样,看来您为方程式元素设置的HTML并未使用innerHTML值:

let add1;
let add2;

function displayNewEquation() {
  add1 = Math.floor(Math.random() * 500);
  add2 = Math.floor(Math.random() * 500);
  // This was the only line change
  document.getElementsByTagName("equation").innerHTML = '<p> ${add1} + ${add2} = </p>';
}

window.onload = () => {
  displayNewEquation();
};

function checkEquation() {
  var input = parseInt(document.getElementById("solution").value);
  console.log(input);
  if (input == add1 + add2) {
    displayNewEquation();
  } else {
    var inputfield = document.getElementById("solution");
    inputfield.style.borderColor = "crimson";
  }
}

function goHome(){
  alert("Do something");
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>mathle</title>
    <link rel="stylesheet" href="Style/Addition.css" />
    <script type="text/javascript" src="./Logic/Addition.js"></script>
  </head>
  <body>
    <div class="additionIntro">
      <p class="title">
        - Addition -
      </p>
      <button class="back" onclick="goHome()">Back</button>
    </div>
    <div class="additionMain">
      <div class="calculation">
        <p class="equation">9 + 13 =</p>
        <input id="solution" type="number" oninput="checkEquation()" />
      </div>
    </div>
  </body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.