根据值更改单元格背景颜色?

时间:2020-08-13 15:13:41

标签: javascript html css

我有这个函数,它接收一个2d数组并创建一个表。我想根据单元格中的值更改单元格背景色。例如(如果cellVal> 0,则将背景更改为绿色)

    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 135, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index_class_helper.pxi", line 109, in pandas._libs.index.Int64Engine._check_type
KeyError: False

2 个答案:

答案 0 :(得分:0)

let transpose_array = [
  [['a', 3], ['b', -2], ['c', 4]], 
  [[1, -3], [2, 2], [3, -1]]
]

function createTable(tableData) {
  var table = document.createElement('table');
  let row;
  let cell;

  tableData.forEach(function (rowData) {
    row = table.insertRow(-1);
    rowData.forEach(function (cellData) {
      cell = row.insertCell();
      
      cell.textContent = cellData[0];
      let cellVal = cellData[1];
      if (cellVal > 0) {
        cell.classList.add('green')
      }
    });
  });
  document.body.appendChild(table);
}
createTable(transpose_array)
.green {
  background-color: green;
 }

答案 1 :(得分:0)

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);

}