Select a cell from the table and giving it unique class

旧城冷巷雨未停 提交于 2020-03-04 19:23:29

问题


I have cells (9x9 rows/cols), and I'm trying to create one cell out of the 49 cells to be unique, as you can see when you run the snippet, the cells have random numbers between 20 to 200, and one of these cells have Red color.

The problem I'm struggling with, I want that one cell to have Symbol (marking plate) like S or D for example instead of number, How i can achieve that?


回答1:


It seems pretty easy as you have a class (uniqueCell) in the element. You can simply target the cell with the class (uniqueCell) and set the innerText or textContent property:

document.querySelector('.uniqueCell').textContent = 'S';

var isCol = 0;
var board = [];
for (r = 0; r < 7; r++) {
  var line = [];
  for (c = 0; c < 7; c++) {
    line.push(RandomGenerator(50, 500));
  }
  board.push(line);
}

function prs(curr, c, r) {
  showTable(curr, c, r);
  isCol = (isCol + 1) % 2;
}

function toColor(col, row, chosen_col, chosen_row) {
  var ret = false;
  switch (isCol) {
    case 0:
      if (row == chosen_row) {
        ret = true;
      }
      break;
    case 1:
      if (col == chosen_col) {
        ret = true;
      }
      break;
  }
  return ret;
}

function showTable(c, chosen_col, chosen_row) {
  var str = "";
  str += "<table border=1>";
  for (row = 0; row < 7; row++) {
    str += "<tr>";
    for (let col = 0; col < 7; col++) {
      str += "<td onclick='prs(this, " + col + "," + row + ")'";
      if (toColor(col, row, chosen_col, chosen_row)) {
        if(c.textContent == board[row][col]){
          str += " class=uniqueCell";
        }
        else str += " class='grn' ";
      }
      str += ">";
      if(c.textContent == board[row][col]){
        str += 'S';
      }
      else str += board[row][col];
      str += "</td>";
    }
    str += "</tr>";
  }
  str += "</table>";

  document.getElementById("ff").innerHTML = str;
}

function RandomGenerator(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

showTable(-1);

var getUnique = function(){
  var tdElements = document.querySelectorAll('#ff td');
  tdElements[
    RandomGenerator(0, tdElements.length)
  ].classList.add('uniqueCell');
  // update the text of the cell using the class
  document.querySelector('.uniqueCell').textContent = 'S';
};
getUnique();
td{
  border:2px solid black;
  width:10px;
  height:10px;
  text-align: center;
}
td:hover{background-color:lightgreen;}
.grn{
  background-color:green;
  color:white;
}

.uniqueCell {
  background-color: tomato;
}
<div id="ff"></div>


来源:https://stackoverflow.com/questions/60376657/select-a-cell-from-the-table-and-giving-it-unique-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!