[嘿,我想构建这个计算器,它应该在页面加载时生成随机数并将其描述在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>
正如@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>