javascript - 根据值更改单元格背景颜色?
问题描述
我有这个函数,它接受一个二维数组并创建一个表。我想根据单元格中的值更改单元格背景颜色。前任。(如果 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;
}
解决方案
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);
}
推荐阅读
- python-3.x - 如何遍历字典以获取存储在 Sqlalchemy 表中的数据?
- python - 用opencv检测两个图像之间的差异
- python - 使用 PIL“PIL.UnidentifiedImageError:无法识别图像文件”打开 Tif 文件
- java - 如何通过引用另一个 HashMap 对 HashMap 进行排序
- java - 创建一个井字游戏应用程序,我有这个错误,它每次都在同一个方块上声明一个平局
- nginx - Nginx 反向代理重定向
- javascript - 无法弄清楚如何返回正确的数组
- c# - '无法对 System.Single 和 System.String 执行 'Like' 操作。
- office-ui-fabric - 在 Fluent UI 中使用类似 Toast 的 UI 小部件
- makefile - 如何在英特尔 Pin 工具中使用(编译)zlib(gzip 函数)压缩库?