如何解决Javascript从数组向表添加行标题?
我有一个2d数组,用于填充表格。有没有一种方法可以在最左边插入一列?
//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;
let cellVal = cellData;
//make cells different shades 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);
}
createTable(transpose_array);
由于颜色条件,我不想向表中添加值,Id就像使用我拥有的数组中的值向表的y轴上的每一行添加标题一样。
解决方法
forEach()
回调获得包含数组索引的第二个参数,您可以使用它来索引标题数组,并将其作为每行的第一个单元格插入。
//function to create the table
function createTable(tableData,row_headings) {
var table = document.createElement('table');
var row = {};
var cell = {};
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 shades 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);
}
createTable(transpose_array,price_array);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。