我想做一个游戏,你可以通过点击方块来找出颜色组合。问题是我无法弄清楚如何让每个单独的正方形改变颜色,而是它们一次全部改变。我看了几个w3schools和Mozilla教程,但他们没有我想要的东西。
let box = document.querySelectorAll('[data-box]')
for (i = 0; i < box.length; i++) {
box[i].addEventListener('click', () => {
box.forEach(color => {
color.style.backgroundColor = "green"
})
})
}
div.box {
height: 100px;
width: 100px;
margin: 10px;
border: 1px solid black;
}
<div class="box" data-box></div>
<div class="box" data-box></div>
<div class="box" data-box></div>
<div class="box" data-box></div>
它们都会立即更改,因为您使用box.forEach()
来指示它们立即更改。
您应该只更改当前点击事件target
的框:
let box = document.querySelectorAll('[data-box]');
for (i = 0; i < box.length; i++) {
box[i].addEventListener('click', (e) => {
e.target.style.backgroundColor = "green";
})
}
div.box {
height: 100px;
width: 100px;
margin: 10px;
border: 1px solid black;
}
<div class="box" data-box></div>
<div class="box" data-box></div>
<div class="box" data-box></div>
<div class="box" data-box></div>
或者,循环访问这些框并在当前迭代目标上调用事件侦听器:
let box = document.querySelectorAll('[data-box]');
box.forEach(b => b.addEventListener('click', () => b.style.backgroundColor = 'green'));
div.box {
height: 100px;
width: 100px;
margin: 10px;
border: 1px solid black;
}
<div class="box" data-box></div>
<div class="box" data-box></div>
<div class="box" data-box></div>
<div class="box" data-box></div>