如何通过一个事件(onclick)设置一般元素的背景颜色并设置同类特定元素的背景颜色?

4

我正在使用HTML/CSS/JS编写一个UltraTicTacToe游戏。它是由嵌套在表格中的表格组成的。当你点击X或O时,我希望下一个TicTacToe表格/游戏被突出显示。我想重置突出显示的表格/游戏为白色,并突出显示另一个表格/游戏。我目前尝试使用一个函数来将所有表格的背景颜色设置为白色,然后将特定的表格设置为黄色,但它拒绝为我工作...有什么想法吗?

function tableReset() {
  document.getElementByClassName('tabler').style.backgroundColor = 'white';
}

function hide1() {
  document.getElementById('o1').style.display = 'none';
}

function reSize1() {
  document.getElementById('x1').style.width = '100%';
}

function nextMove1() {
  document.getElementById('st1').style.backgroundColor = 'yellow';
}
<table class="tabler" id="st1">
  <tr class="topmid">
    <td>
      <button type="button" class="x" id="x1" onclick="hide1(); reSize1(); tableReset(); nextMove1();">X</button>
      <button type="button" class="o" id="o1" onclick="hide2(); reSize2(); tableReset(); nextMove1();">O</button>
    </td>

这里是游戏外观图片 - UltraTICTACTOE

(注:UltraTICTACTOE是游戏名称)

2
切换一个类... - epascarello
document.getElementByClassName() 返回一个 NodeList,而不是单个元素。 - Phil
2个回答

1

getElementsByClassName 返回一个 HTMLCollection。你可以使用 document.getElementsByClassName('tabler')[0] 获取它的第一个元素,或者你可以使用 getElementById

function tableReset() {
  //document.getElementsByClassName('tabler')[0].style.backgroundColor = 'white';
  //or
  document.getElementById('st1').style.backgroundColor = 'white';
}

function hide1() {
  document.getElementById('x1').style.display = 'none';
}
function hide2() {
  document.getElementById('o1').style.display = 'none';
}
function reSize1() {
  document.getElementById('x1').style.width = '100%';
}
function reSize2() {
  document.getElementById('o1').style.width = '100%';
}

function nextMove1() {
  document.getElementById('st1').style.backgroundColor = 'yellow';
}
<table class="tabler" id="st1">
  <tr class="topmid">
    <td>
      <button type="button" class="x" id="x1" onclick="hide1(); reSize1(); tableReset(); nextMove1();">X</button>
      <button type="button" class="o" id="o1" onclick="hide2(); reSize2(); tableReset(); nextMove1();">O</button>
    </td>


那么有没有办法选择所有的表格? - MountainMan
这就是我最终使用的代码,它能够正常工作!感谢您的帮助! var myNodelist = document.querySelectorAll("table"); var i; for (i = 0; i < myNodelist.length; i++) { myNodelist[i].style.backgroundColor = "white"; } - MountainMan
没问题,记得你会得到文档中所有表格元素。 - eag845

0

如果其他人遇到了这个问题,这将选择它们全部!

var myNodelist = document.querySelectorAll("table");
var i;
for (i = 0; i < myNodelist.length; i++) {
    myNodelist[i].style.backgroundColor = "white";
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接