如何使用 queryselectorall 定位我的类名
2021-09-07
580
我不确定为什么我无法使用 document.querySelectorAll 查询选择我的类。
我起初以为是因为它们位于另外两个 div 内,所以我将它们注释掉。但仍然没有结果。定位 elementsById 没有问题。我只用一个按钮测试了这一点,它 console.log 了 button.value。
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 href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:ital@1&display=swap" rel="stylesheet">
</head>
<body>
<div class="heading">
<h1>Calculator!!!!</h1>
</div>
<div class="container">
<div id="calculator" class="calc">
<input type="text" id="userinput" placeholder="0">
<button class="numbers" id= "seven" >7</button>
<button class="numbers" id= "eight">8</button>
<button class="numbers"id= "nine">9</button>
<button class="operator"id= "multiply">*</button>
<button class="numbers" id= "four">4</button>
<button class="numbers" id= "five">5</button>
<button class="numbers" id= "six">6</button>
<button class="operator" id= "subtract">-</button>
<button class="numbers" id= "one">1</button>
<button class="numbers" id= "two">2</button>
<button class="numbers" id= "three">3</button>
<button class ="operator" id= "add">+</button>
<button class ="operator" id= "divide">/</button>
<button id= "clr ()">C</button>
<button id ="del ()">DEL</button>
<button class = "equals" id= "equals">=</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
js
let currentOperator = null;
let firstOperand = null;
let secondOperand = null;
let toBeCleaned = false;
let result = null;
let display = document.getElementById("userinput");
const numberButtons = document.querySelectorAll(".numbers");
const calc = document.querySelector(".calc")
const operators = document.querySelectorAll(".operator");
const equalSign = document.getElementById("equal");
const clearButton = document.getElementById("clear");
numberButtons.onclick = function () {
if (numberButtons.className == "numbers") {
console.log(numberButtons);
}
}
2个回答
querySelectorAll
运行良好,但它返回的是元素列表,而不是单个元素。您不能简单地一次性在整个列表上设置
onclick
;您需要循环遍历它:
numberButtons.forEach((button) => {
button.onclick = function () {
// Handle button click
}
})
Thomas
2021-09-07
您的问题不在于 querySelectorAll。 QuerySelectorAll 返回所有找到的元素的数组。 而您正试图在数组上放置一个 onclick 事件。 这行不通。
要使 onclick 工作,请执行以下操作
numberButtons.forEach(btn => {
btn.onclick = function (evt) {
console.log(evt.target)
}
})
italant
2021-09-07