如何阻止事件触发两次?



我正尝试着创造一款一字棋游戏去理解Dom操纵;我已经在#main-wrapDiv内的所有个人Div上放置了eventListener()。这些div包含一个十字和一个圆圈的SVG,它们都包含CSS值display:none。一旦玩家选择了他的移动,我如何确保所选择的div不能再次被选择?(因为如果它再次被选中,它就会从一个十字变成一个圆)。如果你能想出办法,请帮助我。

const section1 = document.querySelector('.section-one');
const mainDiv = document.getElementById('main-wrap');
let whosGo = 0;
for (prop of mainDiv.children) {
prop.addEventListener('click',addSVGs);

}
function addSVGs(e) {
this.firstElementChild.classList = "cross";
this.firstElementChild.nextElementSibling.classList = "circle-display";
whosGo ++;
if(whosGo % 2 === 0) {
this.firstElementChild.classList = "cross-display";
this.firstElementChild.nextElementSibling.classList = "circle";            
}

}

您应该尝试将用于绘制形状的代码放入else块中。

function addSVGs(e) {
whosGo ++;
if(whosGo % 2 === 0) {
this.firstElementChild.classList = "cross-display";
this.firstElementChild.nextElementSibling.classList = "circle";            
}else{
this.firstElementChild.classList = "cross";
this.firstElementChild.nextElementSibling.classList = "circle-display";
}     
}

最新更新