简体   繁体   English

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

[英]DOM manipulation on first selector only

Building a very basic TicTacToe: Click the desired cell; 构建一个非常基本的TicTacToe:单击所需的单元格;然后单击“确定”。 once for X, again for O, third time for blank. 一次代表X,再次代表O,第三次代表空白。 I can get a function to cycle through the choices but it only targets the first cell, no matter where I click. 我可以使用一个功能来循环选择,但是无论我在哪里单击,它都只针对第一个单元格。

 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> 

Pass this to your add function, and that will contain the current element (or cell) you're clicking in. 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM