![](/img/trans.png)
[英]Using javascript to change table cell background color based on json value
[英]Change cell background color based on value?
我有這個 function 接收一個二維數組並創建一個表。 我想根據單元格中的值更改單元格背景顏色。 前任。 (如果 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;
}
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.