jquery - 动态设置特定单元格的颜色

标签 jquery html

我有一个 17x17 表格,它是使用 jquery 动态生成的。见下文:

enter image description here

下面是我的代码:

$(document).ready(function() {
  var number_of_rows = 17;
  var number_of_cols = 17;
  var table_body = '<table border="0">';
  for (var i = 0; i < number_of_rows; i++) {
    table_body += '<tr>';
    for (var j = 0; j < number_of_cols; j++) {
      table_body += '<td>';
      table_body += '<button id="row_' + i + '" class="col_' + j + '">&nbsp;</button>';
      table_body += '</td>';
    }
    table_body += '</tr>';
  }
  table_body += '</table>';
  $('#tableDiv').html(table_body);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="tableDiv">
  Table will generate here.
</div>

我的问题是,我想将特定单元格的背景色动态设置为红色,如下表所示。我做了一些研究,但仍然找不到解决方案。 enter image description here

最佳答案

设置一个样式变量,如果行数和列数正确,则将其指定为红色背景色:

$(document).ready(function() {
  var number_of_rows = 17;
  var number_of_cols = 17;
  var table_body = '<table border="0">';
  for (var i = 0; i < number_of_rows; i++) {
    table_body += '<tr>';
    for (var j = 0; j < number_of_cols; j++) {

      var style = "";
      if (Math.ceil(i / 3) % 2 !== 0 && j % 4 !== 0) {
        style = "background-color: red;";
      }

      table_body += '<td style="' + style + '">';
      table_body += '<button id="row_' + i + '" class="col_' + j + '" style="' + style + '">&nbsp;</button>';
      table_body += '</td>';
    }
    table_body += '</tr>';
  }
  table_body += '</table>';
  $('#tableDiv').html(table_body);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="tableDiv">
  Table will generate here.
</div>

关于jquery - 动态设置特定单元格的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57780798/

相关文章:

Jquery .css 不在函数内工作

java - 在 Spring MVC Controller 中使用 jquery 传递对象数组

html - 固定顶部+底部导航栏,中间有可滚动内容

javascript - 如何将图像用作用 Canvas 制作的文本的颜色

javascript - 悬停时在html文本中一个一个地改变字母的颜色

javascript - 使用javascript计算宽度并调整css

javascript - 如何禁用 radio 组中的一个 radio 输入?

javascript - 如何将JQuery find 和each 一起使用?

html - 键盘 TAB 选择不可见

php - 在 HTML 表格中显示嵌套数组