Javascript Object for Tic Tac Toe game

后端 未结 3 1737
星月不相逢
星月不相逢 2021-01-29 09:21

Complete newbie here on the Javascript topic. I am trying to code out a Tic Tac Toe game, while using JS\' Objects to save code space. I figured I might create a JS Object which

3条回答
  •  不要未来只要你来
    2021-01-29 10:08

    So funny thing, I have solved this problem with bits of Jeremy Dejno's code, but had to adjust it. Taking into account the HTML code I posted in the first post, here's what worked for me:

    function swap(){
        if (this.textContent === ""){
          this.textContent = "X";
        }else if (this.textContent === "X") {
          this.textContent = "O";
        }else {
          this.textContent = "";
        }
      }
    
    document.querySelectorAll('.gameField').forEach(function(element){
        element.addEventListener('click',swap);
      })
    

    Since this is a completely new thing for me (I am coming from a Python background), can someone tell me if I understand this correctly: After calling .addEventListener on every item with .gameField class, a swap function is called on every click event on any of them, and the swap function can be called without any arguments because THIS keyword makes it try to modify .textContent property of whatever object it is called on?

提交回复
热议问题