我目前正在尝试为计算器项目添加2个功能:
-
当数字按钮被点击时,它将显示在计算器gui上
-
将该值添加到变量"num"
在GetNumber函数中,当我单击一个按钮时,这一行成功地将该数字输出到步骤1的计算器上。
outputBox.textContent += e.target.classList[1]
我正在努力的是获得"num"的返回值。我在这里做了同样的事情,当我console.log(num)时,它可以很好地输出数字,但是当我试图返回"num">
num += e.target.classList[1]
参考这里的代码。我正在用equals函数测试它,这样当在计算器上单击equals按钮时,如果工作正常,它应该将数字输出到控制台中。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="calcContainer">
<div id="outputBox">
</div>
<div class="buttons">
<button class="number 7">7</button>
<button class="number 8">8</button>
<button class="number 9">9</button>
<button class="operator ÷">÷</button>
<button class="number 4">4</button>
<button class="number 5">5</button>
<button class="number 6">6</button>
<button class="operator x">x</button>
<button class="number 1">1</button>
<button class="number 2">2</button>
<button class="number 3">3</button>
<button class="operator -">-</button>
<button class="number 0">0</button>
<button id="clear">AC</button>
<button id="equals">=</button>
<button class="operator +">+</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
JS
let outputBox = document.getElementById("outputBox");
const number = document.getElementsByClassName("number");
const operator = document.getElementsByClassName("operator");
const equalsButton = document.getElementById("equals")
let a = "", middle = "", b = "", runningTotal = 0
function getNumber(num) {
for (let i = 0; i < number.length; i++) {
number[i].addEventListener("click", (e) => {
outputBox.textContent += e.target.classList[1]
num += e.target.classList[1]
console.log(num)
})
}
return num
}
a = getNumber(a)
function equals(abc) {
equalsButton.addEventListener("click", () => {
console.log(abc)
})
}
equals(a)
也许你可以试试这个方法?
let a = "", middle = "", b = "", output = "", num = ""
for (let i = 0; i < number.length; i++) {
number[i].addEventListener("click", (e) => {
outputBox.textContent += e.target.classList[1]
num += e.target.classList[1]
output = num
})
}
equalsButton.addEventListener("click", () => {
console.log(output)
})
这是修复您的问题的新代码。
let outputBox = document.getElementById("outputBox");
const numberContainer = document.getElementById("numbers");
const operator = document.getElementsByClassName("operator");
const equalsButton = document.getElementById("equals")
let a = "", middle = "", b = "", runningTotal = 0;
function getNumber(num) {
return (e) => {
outputBox.textContent += e.target.textContent;
num += e.target.textContent;
console.log(num);
};
}
for (let i = 0; i < numberContainer.children.length; i++) {
numberContainer.children[i].addEventListener("click", getNumber(a));
}
function equals(abc) {
equalsButton.addEventListener("click", () => {
console.log(abc)
})
}
equals(a);