董事会是父级 我正在尝试制作一个按钮,从类中删除红色和黄色部分
<div id="board">
<div id="0-0" class="tile"></div>
<div id="0-1" class="tile red-piece"></div>
<div id="0-2" class="tile yellow-piece"></div>
//etc...
</div>
这是我的尝试,我制作了一个按钮,单击时调用此函数resetButton.addEventListener('click', resetGame)
请告诉我如何修复它 尝试:
function resetGame(){
board.appendChild.classList.remove('red-piece')
board.appendChild.classList.remove('yellow-piece')
}
编辑:只是想提一下,这是代码的一部分,我已经给了他们变量/查询选择器并制作了必要的CSS,板div下面的div也是使用JS中的for循环创建的,这是我的尝试在不使用研究所项目教程的情况下制作 Connectfour 游戏。我也不知 Prop 体如何使用appendChild。 感谢大家的回复
最佳答案
- 不要使用
.appendChild()
将元素添加到它们已经所在的 DOM 中。 - 定位每个
.tile
document.querySelectorAll(".tile").forEach(tile => //...
- 您可以在
.add()
和.remove()
中使用多个参数/*...*/ tile.classList.remove("red", "gold");
document.querySelector(".reset").onclick = resetBoard;
function resetBoard(event) {
document.querySelectorAll(".tile").forEach(tile => {
tile.classList.remove("red", "gold");
});
}
main {
display: grid;
grid-template-columns: repeat(5, 1fr);
grid-template-rows: repeat(5, 1fr);
grid-column-gap: 0px;
grid-row-gap: 0px;
width: max-content;
border: 2px ridge #ddd;
}
.tile {
width: 50px;
height: 50px;
border: 2px inset #ddd;
}
.red {
background-color: red;
}
.red:hover {
background-color: rgba(255, 0, 0, 0.5);
transition: 0.3s;
}
.gold {
background-color: gold;
}
.gold:hover {
background-color: rgba(255, 215, 0, 0.5);
transition: 0.3s;
}
.reset {
display: block;
width: 270px;
font: inherit;
cursor: pointer;
}
<button class="reset">RESET</button>
<main>
<div class="tile red"></div>
<div class="tile gold"></div>
<div class="tile red"></div>
<div class="tile gold"></div>
<div class="tile red"></div>
<div class="tile gold"></div>
<div class="tile red"></div>
<div class="tile gold"></div>
<div class="tile red"></div>
<div class="tile gold"></div>
<div class="tile red"></div>
<div class="tile gold"></div>
<div class="tile red"></div>
<div class="tile gold"></div>
<div class="tile red"></div>
<div class="tile gold"></div>
<div class="tile red"></div>
<div class="tile gold"></div>
<div class="tile red"></div>
<div class="tile gold"></div>
<div class="tile red"></div>
<div class="tile gold"></div>
<div class="tile red"></div>
<div class="tile gold"></div>
<div class="tile red"></div>
</main>
关于javascript - 如何从子元素中删除特定类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74059976/