我试图创建一个简单的计数计数器,为“名称”数组中的每个人创建相同的按钮集。
javascript
var names = ["Andrew", "Ryan", "Brandon", "Jason", "Justin", "Sarah", "William", "Jonathan", "Stephanie", "Brian", "Nicole", "Nicholas", "Anthony", "Heather", "Eric", "Elizabeth", "Adam", "Megan", "Melissa", "Kevin", "Steven", "Thomas", "Timothy", "Christina", "Kyle", "Rachel", "Laura", "Lauren", "Amber", "Brittany", "Danielle", "Richard", "Kimberly", "Jeffrey", "Amy", "Crystal"];
function Buttons() {
var List = document.getElementById('container');
List.innerHTML=''
names.forEach((name) => {
List.innerHTML += name + '<div> <div class="counter">0</div> <button class="add">Add</button><button class="minus">Minus</button><br><button class="reset">Reset</button></div>'
});
};
Buttons();
let counter = document.querySelectorAll(".counter");
let add = document.querySelectorAll(".add");
let minus = document.querySelectorAll(".minus");
let reset = document.querySelectorAll(".reset");
add.forEach(addButton => {
addButton.addEventListener('click', addCounter);
});
minus.forEach(minusButton => {
minusButton.addEventListener('click', minusCounter);
});
reset.forEach(resetButton => {
resetButton.addEventListener('click', resetCounter);
});
function addCounter() {
counterNum = counter.innerHTML
counter.innerHTML = parseInt(counterNum) + 1
}
function minusCounter() {
counterNum = counter.innerHTML
if (counterNum == 0){
return false
}
counter.innerHTML = parseInt(counterNum) - 1
}
function resetCounter() {
counter.innerHTML = 0;
};
html
<body>
<h1>Tally Counter</h1>
<div id="container"></div>
<script src="/script.js"></script>
</body>
</html>
当我点击按钮时,什么也没发生。当我将计数器变量上的queryselectorall更改为just queryselector时,它仅对第一人称有效。我做错了什么?有没有更好的方法?
1条答案
按热度按时间gcmastyq1#
您正在设置一个名为“counter”的变量,并为其分配div元素(所有class='counter'元素)的html集合。因此,您的单击侦听器函数不知道要使用哪个计数器。
访问与其他元素(如按钮)关联的元素(如计数器div)的最佳方法是使用相对路径,例如:单击按钮时,找到与其分组的计数器并修改它。你可以用它来做
closest()
(遍历元素的父元素直到找到匹配项)与querySelector()
这里是一个轻微的重写,希望向您展示如何最小化代码的易读性,以及如何访问所需的计数器。