【问题标题】:How do you properly execute removeEventListener in this case?在这种情况下,您如何正确执行 removeEventListener?
【发布时间】:2022-12-04 08:23:56
【问题描述】:

我是编码新手,这里是一个简单的井字游戏的非常基本的代码:

function game(id) {
    let round = '';
    round = playRound(id, getComputerChoice());
    if(round == "win") {
        win++;
    } else if(round == "lose") {
        lose++;
    }
    score.textContent = "Score is " + win + "-" + lose;
    if(win == 5) {
        over.textContent = "Game is over, you win!";
    } else if(lose == 5) {
        over.textContent = "Game is over, you lose!";
    }
}

let win = 0;
let lose = 0;
const result = document.querySelector('#results');
const buttons = document.querySelectorAll('button');
const score = document.querySelector('#score');
const over = document.querySelector('#over');
buttons.forEach((button) => {
    button.addEventListener('click', () => game(button.id));
});

playRound 返回获胜、失败或平局,getComputerChoice 返回计算机的随机选择。一旦任一玩家到达 5,我想使用 removeEventListener 将页面保持原样,但我无法正确使用它。

我也不知道我的代码是否是编写这个程序的最佳方式。非常感谢任何有关如何优化/更好地编写此程序的建议。谢谢你。

我试过这样坚持 removeEventListener,但它没有按预期工作:

function game(id) {
    ...
    if(win == 5) {
        over.textContent = "Game is over, you win!";
        button.removeEventListener('click', () => game(button.id));
    } else if(lose == 5) {
        over.textContent = "Game is over, you lose!";
        button.removeEventListener('click', () => game(button.id));
    }
}

我知道这是非常错误的,但这是我能想到的唯一方法。我在网上浏览了参考页面,但无法理解。谢谢你的帮助。

【问题讨论】:

    标签: javascript dom


    【解决方案1】:

    虽然您可以将所有 5 个处理程序保存在一个函数数组中,然后遍历它们以在最后删除,或者使用事件委托并只删除一个事件处理程序 - 为什么不直接检查 game 是否已达到任一限制在继续之前?

    function game(id) {
      if (win === 5 || lose === 5) {
        return;
      }
      // ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-27
      • 1970-01-01
      • 2020-08-06
      • 2012-06-06
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多