【问题标题】:How to stop an event from firing twice?如何阻止事件触发两次?
【发布时间】:2021-04-22 01:14:36
【问题描述】:

我正在尝试制作井字游戏以了解 Dom 操纵; 我在#main-wrap div 内的所有单个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";            
        }
      
    }

【问题讨论】:

    标签: javascript css events logic dom-events


    【解决方案1】:

    您应该尝试将用于绘制形状的代码放入 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";
         }     
    }
    

    【讨论】:

    • 您好!我尝试了该代码 sn-p 但结果相同,但感谢您的帮助:)
    猜你喜欢
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 2015-03-18
    • 2011-02-06
    • 2014-04-07
    • 1970-01-01
    相关资源
    最近更新 更多