您好,我有一些代码在井字游戏中的div中标记“ X”或“ O”,但是该功能在第一次单击时未执行,而是在第二次单击时开始

我已经浏览了其他提出的问题
但没有找到与我的代码相关的任何内容

任何帮助将不胜感激

function setX() {
    $('#container').on('click', function (e) {

        if (this !== e.target) e.target.textContent = 'X';

    });
    event.stopPropagation();
}

function setO() {
    $('#container').on('click', function (e) {

        if (this !== e.target) e.target.textContent = 'O';

    });
    event.stopPropagation();
}




这是我的代码,每次单击功能之间切换

let myFunctions = [setO, setX, setO, setX, setO, setX, setO, setX, setO, setX, setO]
let nextFunction = 0;

function myFunctionSwitcher() {
    myFunctions[nextFunction]();
    nextFunction = nextFunction + 1;
}

container.addEventListener('click', () => {
    myFunctionSwitcher();
    // whoWon()

});

最佳答案

就像comments中已经指出的那样,您每次单击都将添加事件侦听器,而不是设置XO。无需过多更改当前代码,您可以执行以下操作:

function setX(element, event) {
  // don't set an onclick event here
  if (element !== event.target) event.target.textContent = 'X';
}

function setO(element, event) {
  // don't set an onclick event here
  if (element!== event.target) event.target.textContent = 'O';
}

let myFunctions = [setO, setX, setO, setX, setO, setX, setO, setX, setO, setX, setO];

function myFunctionSwitcher(element, event) {
    // pass the element and event forward to setO or setX
    myFunctions[nextFunction](element, event);
    nextFunction = nextFunction + 1;
}

$('#container').on('click', function (event) {
    // pass this and the event to myfunction
    myFunctionSwitcher(this, event);
    // whoWon()
});


您可以使自己更轻松,而可以执行以下操作:

// creates a toggle function toggling between `a` and `b`, starting at `a`
function toggleValues(a, b) {
  var toggle = false;
  return function () {
    toggle = !toggle;
    return toggle ? a : b; // ternary if
  };
}

const toggleOX = toggleValues('O', 'X');
$('#container').on('click', function (event) {
  if (this !== event.target) event.target.textContent = toggleOX();
  // whoWon()
});

09-25 19:09