【问题标题】:Changing a table cell colour ifdepending on its neighbours根据其邻居更改表格单元格颜色
【发布时间】:2018-12-17 23:57:30
【问题描述】:

这是我的代码:

var row = [
  [4, 7, 2, 6, 2, 1, 9, 0],
  [6, 1, 5, 0, 4, 3, 7, 1],
  [0, 3, 2, 1, 8, 2, 8, 4],
  [8, 9, 4, 5, 3, 0, 5, 0],
  [4, 6, 7, 8, 6, 7, 3, 9],
  [9, 3, 2, 0, 1, 5, 8, 7],
  [6, 1, 9, 7, 4, 9, 2, 4],
  [2, 8, 6, 5, 3, 0, 6, 5],
  [0, 3, 4, 8, 2, 5, 3, 9]
];

var text = "<table id='swertrestable'>";

for (i = 0; i < 9; i++) {
  text += "<tr>";
  for (x = 0; x < 8; x++) {
    text += "<td>" + row[i][x] + "</td>";
  }
  text += "</tr>";
}

text += "</table>";

document.getElementById("demo").innerHTML = text;

function findNumbers() {

  var lastcombination = document.getElementById('lastresult').value;
  var output = [];
  var sNumber = lastcombination.toString();

  for (var y = 0, len = sNumber.length; y < len; y += 1) {
    output.push(+sNumber.charAt(y));
  }

  var no1 = parseInt(output[0]);
  var no2 = parseInt(output[1]);
  var no3 = parseInt(output[2]);

  var table = document.getElementById("swertrestable");
  var rows = table.getElementsByTagName("tr");
  for (var i = 0, row; row = table.rows[i]; i++) {
    for (var j = 0, col; col = row.cells[j]; j++) {
      rows[i].cells[j].classList.remove("red");
      if (parseInt(col.innerHTML) == no1 || parseInt(col.innerHTML) == no2 || parseInt(col.innerHTML) == no3) {
        rows[i].cells[j].className = 'red';
      }
    }
  }

}
table,
th,
td {
  border: 2px solid black;
  border-collapse: collapse;
}

td {
  padding: 10px 20px;
}

td.red {
  color: #fff;
  background-color: #f00;
}

td.blue {
  color: #fff;
  background-color: #3498db;
}

td.redtoblue {
  color: #fff;
  background-color: #3498db;
}
<p id="demo"></p>
<h2>INPUT 3 DIGITS</h2><br>
<input type="text" name="lastresult" id="lastresult">
<button onclick="findNumbers()">Submit</button>

它的作用是迭代表,获取其值并将其与no1no2no3 进行比较,如果相等,它将添加一个名为"red" 的类名,它会更改背景颜色将单元格变为红色。

现在,我想做的只是将类添加到相邻单元格的 3 个组合(顶部、底部、左侧、右侧)。我认为下面的图像会更清晰。

这个的正确循环是什么?

【问题讨论】:

  • 如果您发布了minimal reproducible example,会更容易提供帮助。你可以使用&lt;&gt;sn-p 编辑器
  • 您好 mplungjan,感谢您提供的信息!我是 Stack Overflow 的新手,这个功能真的很有帮助!更新了它。请立即检查。
  • 涉及的编码过多。我会使用i.x 为每个单元格添加一个ID(PS:请在任何地方使用i,j)并使用var reds = document.querySelectorAll(".red"); for (var i=0;i&lt;reds.length;i++) { var id = reds[i].id; var coordinates = id.split("."); var topId = (coordinates[0]-1)+"."+coordinates[1], botId = (coordinates[0]+1,+"."+coordinates[1], lftId = coordinates[0]+"."+(coordinates[1]-1), rgtId = coordinates[0]+"."+(coordinates[1]+1); 之类的代码,然后您可以测试neighbours.classList.contains("red")
  • 在我看来,最简单的方法是创建一个函数 hasNeighbor() 来检查每个相邻单元格 (x+1, x-1, y+1, y-1) 是否有数字是有效的,如果一个有效则返回 true(确保不检查越界单元格 (x=-1)...)。然后,您只需将类 Red 添加到具有邻居的单元格中。此解决方案不是最优化的解决方案,但易于阅读和理解。
  • @mplungjan 我会测试这个解决方案!谢谢

标签: javascript html loops html-table


【解决方案1】:

不是太经典的解决方案,但有效!请尝试。

    var row = [
      [4, 7, 2, 6, 2, 1, 9, 0],
      [6, 1, 5, 0, 4, 3, 7, 1],
      [0, 3, 2, 1, 8, 2, 8, 4],
      [8, 9, 4, 5, 3, 0, 5, 0],
      [4, 6, 7, 8, 6, 7, 3, 9],
      [9, 3, 2, 0, 1, 5, 8, 7],
      [6, 1, 9, 7, 4, 9, 2, 4],
      [2, 8, 6, 5, 3, 0, 6, 5],
      [0, 3, 4, 8, 2, 5, 3, 9]
    ];

    var text = "<table id='swertrestable'>";

    for (i = 0; i < 9; i++) {
      text += "<tr>";
      for (x = 0; x < 8; x++) {
        text += "<td>" + row[i][x] + "</td>";
      }
      text += "</tr>";
    }

    text += "</table>";

    document.getElementById("demo").innerHTML = text;

    function findNumbers() {
        // remove previous red or blue classes
        var elems = document.querySelectorAll(".blue");
        [].forEach.call(elems, function(el) {
            el.classList.remove("blue");
        });

        var elems = document.querySelectorAll(".red");

        [].forEach.call(elems, function(el) {
            el.classList.remove("red");
        });    

      var lastcombination = document.getElementById('lastresult').value;
      var output = [];
      var sNumber = lastcombination.toString();

      for (var y = 0, len = sNumber.length; y < len; y += 1) {
        output.push(+sNumber.charAt(y));
      }

      var no1 = parseInt(output[0]);
      var no2 = parseInt(output[1]);
      var no3 = parseInt(output[2]);

      var numArr = new Array(no1,no2,no3);

      var rightCell, leftCell, topCell, bottomCell, thisCell;

      var table = document.getElementById("swertrestable");
      var rows = table.getElementsByTagName("tr");
      for (var i = 0, row; row = table.rows[i]; i++) {
        for (var j = 0, col; col = row.cells[j]; j++) {
          //rows[i].cells[j].classList.remove("red");
          rows[i].cells[j].classList.remove("blue");

          thisCell = parseInt(col.innerHTML);

          if(row.cells[j+1]) {
            rightCell = parseInt((row.cells[j+1]).innerHTML);
          }
          else {
            rightCell = ""    ;
          }

          if(row.cells[j-1]) {
            leftCell = parseInt((row.cells[j-1]).innerHTML);    
          }
          else {
            leftCell = "";    
          }

          if(rows[i-1]) {
               topCell = parseInt((rows[i-1].cells[j]).innerHTML);
          }
          else {
               topCell = "";
          }
          if(rows[i+1]) {
             bottomCell = parseInt((rows[i+1].cells[j]).innerHTML);
          }
          else {
             bottomCell = "";    
          }

          //if (parseInt(col.innerHTML) == no1 || parseInt(col.innerHTML) == no2 || parseInt(col.innerHTML) == no3) {
          var thisNum = numArr.indexOf(thisCell);
          if( thisNum !== -1)    {

            var neighbours = 0;

            if ((topCell == no1 || topCell == no2 || topCell == no3) && topCell!=thisCell) {
               neighbours++;
            }
            if ((leftCell == no1 || leftCell == no2 || leftCell == no3) && leftCell!==thisCell) {
               neighbours++;
            }
            if ((rightCell == no1 || rightCell == no2 || rightCell == no3) && rightCell!==thisCell) {
               neighbours++;
            }        
            if ((bottomCell == no1 || bottomCell == no2 || bottomCell == no3) && bottomCell!==thisCell) {
               neighbours++;
            } 

            if(neighbours===2) {            
                if(topCell!=="" && numArr.indexOf(topCell)!== -1 ) { rows[i-1].cells[j].className = 'red';}
                if(leftCell!=="" && numArr.indexOf(leftCell)!== -1) { rows[i].cells[j-1].className = 'red'; }
                if(rightCell!=="" && numArr.indexOf(rightCell)!== -1) { rows[i].cells[j+1].className='red'; }
                if(bottomCell!=="" && numArr.indexOf(bottomCell)!== -1) { rows[i+1].cells[j].className = 'red'; }

                rows[i].cells[j].className = 'red';
            }
            else {

                var thisClass = rows[i].cells[j].className;
                if(thisClass != 'red') {
                    rows[i].cells[j].className = 'blue';
                }
            }

          }     

        }
      }

    }

【讨论】:

  • 嗨,Tshah,我已经测试过了,它有时有效,但有时无效。见截图prntscr.com/k5mjnm
  • 不幸的是,我明天才能检查这个。我注意到,你已经从我的代码中交换了颜色。会不会是你错过了一个地方?
  • 是的,我换了颜色,因为我只会使用红色的 :) 我认为最好的例子是提交 789
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-11
  • 2023-03-14
  • 2013-10-18
  • 2019-07-15
  • 2018-08-15
  • 2014-07-20
相关资源
最近更新 更多