简体   繁体   中英

Change cell background color based on value?

I have this function that takes in a 2d array and creates a table. I want to change the cell background color based on the value in the cell. ex. (if cellVal > 0 change background to green)

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

}

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM