我正在构建一个计算器,目前我被困在一个特定的问题。当我点击计算器窗口时,我无法让数字填充。
我很难理解查询选择器和事件侦听器,所以我假设我在Javascript的某个地方犯了错误。
我已经创建了一个针对.window-content类的查询选择器。windowValue变量开始时为空白。然后,我有一个用于容纳计算器的容器的查询选择器,其中有一个等待单击的事件侦听器。
问题代码如下:
const screen = document.querySelector(".window-content");
let windowValue = "";
document.querySelector(".container").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.tagName !== "button") return;
let buttonText = tgt.innerText;
if (buttonText == 'X') {
buttonText = '*';
windowValue += buttonText;
screen.value = windowValue;
} else if (buttonText == 'CA') {
windowValue = "";
screen.value = windowValue;
} else if (buttonText == '🡄') {
windowValue = windowValue.slice(0,-1);
screen.value = windowValue;
} else if (buttonText == '=') {
screen.value = operate(firstNum, secondNum, operator);
windowValue = screen.value;
firstNum = "";
operator = "";
secondNum = "";
} else if (buttonText.match(/[0-9]/)) {
windowValue += buttonText;
screen.value = windowValue;
} else {
firstNum = windowValue;
operator = buttonText;
windowValue = "";
windowValue += buttonText;
windowContent.innerText = windowValue;
}
})
我认为错误是你使用querySelector
,这样你只能在第一个元素上应用addEventListener
,而不是所有具有.container
类的元素。只需将其替换为querySelectorAll
并创建一个循环以将click
事件应用于所有button
。
const screen = document.querySelector(".window-content");
let windowValue = "";
[...document.querySelectorAll(".container")].forEach(function (container) {
container.addEventListener("click", function(e) {
const tgt = e.target;
console.log(tgt);
//if (tgt.tagName !== "button") return;
let buttonText = tgt.innerText;
console.log(buttonText);
if (buttonText == 'X') {
buttonText = '*';
windowValue += buttonText;
screen.value = windowValue;
} else if (buttonText == 'CA') {
windowValue = "";
screen.value = windowValue;
} else if (buttonText == '🡄') {
windowValue = windowValue.slice(0,-1);
screen.value = windowValue;
} else if (buttonText == '=') {
screen.value = operate(firstNum, secondNum, operator);
windowValue = screen.value;
firstNum = "";
operator = "";
secondNum = "";
} else if (buttonText.match(/[0-9]/)) {
windowValue += buttonText;
screen.value = windowValue;
} else {
firstNum = windowValue;
operator = buttonText;
windowValue = "";
windowValue += buttonText;
windowContent.innerText = windowValue;
}
});
});
.btn {
display: flex;
}
.container {
display: inline-block;
}
<div class="btn">
<button class="container">X</button>
<button class="container">CA</button>
<button class="container">🡄</button>
<button class="container">=</button>
<button class="container">1</button>
<button class="container">2</button>
<button class="container">3</button>
<button class="container">4</button>
<button class="container">5</button>
<button class="container">6</button>
<button class="container">7</button>
<button class="container">8</button>
<button class="container">9</button>
<button class="container">0</button>
</div>
<br />
<textarea class="window-content"></textarea>