我有通用数据,我只使用Javascript从它构建html表:
HTML:
<div id="container"></div>
使用Javascript:
var dataset = [ { "field1":"val1", "field2":"val2", "field3":"val3" }, { "field1":"val4", "field2":"val5", "field3":"val6", "field4":"val7" } ] ;
function addHeaders(table, keys) {
var row = table.insertRow();
for( var i = 0; i < keys.length; i++ ) {
var cell = row.insertCell();
cell.appendChild(document.createTextNode(keys[i]));
}
}
var max_keys = 0;
var max_idx = 0;
for( var i = 0; i < dataset.length; i++ ) {
var child = dataset[i];
cur_keys = Object.keys(child).length;
if (cur_keys > max_keys) {
max_keys = cur_keys;
max_idx = i;
}
}
var table = document.createElement('table');
addHeaders(table, Object.keys(dataset[max_idx]));
for( var i = 0; i < dataset.length; i++ ) {
var child = dataset[i];
var row = table.insertRow();
Object.keys(child).forEach(function(k) {
var cell = row.insertCell();
cell.appendChild(document.createTextNode(child[k]));
})
}
document.getElementById('container').appendChild(table);
如何允许用户对列升序和降序进行排序?
更新: 排序代码工作的字符串,但不是数字!!
dataset.sort(function (a, b) {
var nameA = Number(a.field2);
var nameB = Number(b.field2);
return (nameA - nameB);
});
答案 0 :(得分:0)
我事先sort数据集(dataset.sort(...)
),并在每次排序顺序(和数据集)发生变化时重新创建表格行。
或者像使用Bootstrap表一样使用能够完成此操作的东西。
Bootstrap - How to sort table columns
修改强>
使用纯JavaScript进行排序:
const dataset = [ { "field1":1, "field2":"val2", "field3":"val3" }, { "field1":4, "field2":"val5", "field3":"val6", "field4":"val7" } ];
Asc(field1):dataset.sort((a,b) => a.field1 - b.field1)
Desc(field1):dataset.sort((a,b) => b.field1 - a.field1)
<强> EDIT2:强>
如果您正在使用字符串,请记得首先将它们转换为Number
:
dataset.sort((a,b) => Number(a.field1) - Number(b.field1))