仅在第一个选择器上操作DOM

问题描述 投票:0回答:1

构建一个非常基本的TicTacToe:单击所需的单元格;一次为X,再次为O,第三次为空白。我可以获得一个循环选择的功能,但它只针对第一个单元格,无论我在哪里单击。

var choices = ['_','X','O'];
var i = 0;
var cell = document.querySelector("td");

function add(){
 cell.innerHTML= choices[i];
  i++;
    if(i > 2){
  i = 0;
  }
}
td{
  width: 100px;
  height: 100px;
  text-align: center;
  font-size:3em;
 
}

#two, #five, #eight{
  border-right: solid black 1px;
  border-left: solid black 1px
}
#four, #six, #five{
  border-top: solid black 1px;
  border-bottom: solid black 1px
}
<table>
  <tr>
    <td class="cell" id ="one" onclick="add()"></td>
    <td class="cell" id="two" onclick="add()"></td>
    <td class="cell" id="three" onclick="add()"></td>
  </tr>
  <tr>
    <td class="cell" id="four" onclick="add()"></td>
    <td class="cell" id="five" onclick="add()"></td>
    <td class="cell" id="six" onclick="add()"></td>
  </tr>
  <tr>
    <td class="cell" id="seven" onclick="add()"></td>
    <td class="cell" id="eight" onclick="add()"></td>
    <td class="cell" id="nine" onclick="add()"></td>
  </tr>
</table>
javascript dom tic-tac-toe
1个回答
0
投票

this传递给你的add函数,它将包含你点击的当前元素(或单元格)。

var choices = ['_','X','O'];
var i = 0;

function add(cell){
 cell.innerHTML= choices[i];
  i++;
    if(i > 2){
  i = 0;
  }
}
td{
  width: 100px;
  height: 100px;
  text-align: center;
  font-size:3em;
 
}

#two, #five, #eight{
  border-right: solid black 1px;
  border-left: solid black 1px
}
#four, #six, #five{
  border-top: solid black 1px;
  border-bottom: solid black 1px
}
<table>
  <tr>
    <td class="cell" id ="one" onclick="add(this)"></td>
    <td class="cell" id="two" onclick="add(this)"></td>
    <td class="cell" id="three" onclick="add(this)"></td>
  </tr>
  <tr>
    <td class="cell" id="four" onclick="add(this)"></td>
    <td class="cell" id="five" onclick="add(this)"></td>
    <td class="cell" id="six" onclick="add(this)"></td>
  </tr>
  <tr>
    <td class="cell" id="seven" onclick="add(this)"></td>
    <td class="cell" id="eight" onclick="add(this)"></td>
    <td class="cell" id="nine" onclick="add(this)"></td>
  </tr>
</table>
© www.soinside.com 2019 - 2024. All rights reserved.