创建 table 并使用 JavaScript 更改 <td> 背景颜色

Create table and change <td> background color using JavaScript

我的任务是这样的:我想创建一个带有按钮和从 1 到 20 的水平 table 结果的页面。

当你点击一个按钮时,你会得到一个随机数,将它显示在页面上,带有这个数字的单元格应该变成绿色。如果该数字第二次出现,将其设为灰色。

如果单元格已经是灰色,则什么也不会发生。就是这样 my code 如果可以,请帮助我。谢谢

您可以在点击时使用 am if 语句

<td onclick:"checkClass(this)"></td>/*Example of your td*/

function checkClass(this){
    /*check if class element is already green*/
    if($(this).attr("class")=="green")
    {
      /*if so them change to gray*/
      $(this).attr("class","gray") ; 
    }
    else if($(this).attr("class")=="gray")
    {
     /*do noting*/
    }
    else
    {
      /*first time you click set green*/
      $(this).attr("class","gray");
    }
}

使用 if 检查该区域是否已经是绿色或灰色,并决定相应的操作:

      if(!numbs.getElementsByTagName("td")[i].getAttribute("class")) {
        numbs.getElementsByTagName("td")[i].setAttribute("class", "green");
      } else if(numbs.getElementsByTagName("td")[i].getAttribute("class") == "green") {
        numbs.getElementsByTagName("td")[i].setAttribute("class", "grey");
      } else {
        // do nothing.. 
      }

查看JSFiddle

ps:你几乎没有使用 jQuery,主要是 vanilla JS。

试试这个

function cheack(){  
  var randNumb = (Math.floor(Math.random()*20)+1);
  var numbs = $(document).find('td')[randNumb];
  var c = $(".green").index("td");

  if ((!$(numbs).hasClass('green')) && (!$(numbs).hasClass('grey')))
    {
      $(numbs).addClass('green');
    }
else
  {
    $(numbs).addClass('grey');
  }

}

http://jsbin.com/rubomehura/1/