首页 > 解决方案 > 根据值更改单元格背景颜色?

问题描述

我有这个函数,它接受一个二维数组并创建一个表。我想根据单元格中的值更改单元格背景颜色。前任。(如果 cellVal > 0 将背景更改为绿色)

//function to create the table
function createTable(tableData) {
  var table = document.createElement('table');
  var row = {};
  var cell = {};

  tableData.forEach(function (rowData) {
    row = table.insertRow(-1);
    rowData.forEach(function (cellData) {
      cell = row.insertCell();

      cell.textContent = cellData;
    });
  });
  document.body.appendChild(table);
}
createTable(transpose_array)

//css
td {
  border: 1px solid black;
  padding: 4px;
  text-align: center;
  vertical-align: middle;
  width: 20px;
  height: 20px;
}
table {
    border-collapse: collapse;
    border-spacing: 0;

}

标签: javascripthtmlcss

解决方案


tableData.forEach(function (rowData,i) {
    row = table.insertRow(-1);
    cell = row.insertCell();
    cell.textContent = row_headings[i];

    rowData.forEach(function (cellData) {
      cell = row.insertCell();
      cell.textContent = cellData;
      let cellVal = cellData;
      //make cells different shaeds of green and red for pos/neg (based on %)
      if (cellVal > 0) {
        cell.style.backgroundColor = '#00e100';
      } else if (cellVal < 0) {
        cell.style.backgroundColor = 'red';
      }
    });
  });
 document.body.appendChild(table);

}

推荐阅读