JS根据数据动态对齐每一列



从后端接收到的消息如下:

[
{
"Name": "ABC",
"ColumnType": "NUMBER"
},
{
"Name": "XYZ",
"ColumnType": "STRING"
},
{
"Name": "EFG",
"ColumnType": "NUMBER"
},
{
"Name": "JKL",
"ColumnType": "STRING"
},
{
"Name": "TOP",
"ColumnType": "TIMESTAMP"
},

]

"Name"作为表中的列名,列中的数据按列类型对齐,即For a ColumnType "NUMBER"one_answers";TIMESTAMP"右对齐并为columntype "STRING"左对齐。

我已经试过了,

var td = document.getElementsByTagName('td');
let tdArr = Array.from(td);
for (var item in snapshot) {
let DataHeader = snapshot[item].DataHeader;
for(let x in DataHeader){
let colType = snapshot[item].DataHeader[x].columnType;
for(let z in tdArr){
if(colType === 'STRING' && colType !== 'NUMBER'){
tdArr[z].style.textAlign= "left";
}
else if(colType === 'NUMBER' && colType !== 'STRING'){
tdArr[z].style.textAlign= "right";
}
else if(colType === 'TIMESTAMP'){
tdArr[z].style.textAlign= "right";
}
}
}
}

这将设置所有的tds为左对齐或右对齐。我该如何解决这个问题?我知道我正在设置所有td元素,但我不确定如何获取特定列的td元素。

上面显示的消息是具有DataHeader的快照对象的一部分。DataHeader包含"名称"。和"columntype">

当使用。foreach()或。map()时,您可以将索引作为第二个参数,这可能非常有用

let columnInfos = [
{
"Name": "ABC",
"ColumnType": "NUMBER"
},
{
"Name": "XYZ",
"ColumnType": "STRING"
},
{
"Name": "EFG",
"ColumnType": "NUMBER"
}
]
columnInfos.forEach((columnInfo, index) => {
let columnType = columnInfo.ColumnType
let tds = Array.from(document.querySelectorAll(`td:nth-of-type(${index+1})`))
if(columnType === 'NUMBER' || columnType === 'TIMESTAMP') {
tds.forEach(td => td.style.textAlign = 'right')
}else if(columnType === 'STRING'){
tds.forEach(td => td.style.textAlign = 'right')
}
})

相关内容

  • 没有找到相关文章

最新更新