我需要按名称对表格进行排序。对于排序,我使用函数
function sortArray(index) {
let arr = [];
rows.forEach( elem => {
arr.push(elem.children[index].textContent);
})
let sort = arr.sort( (a, b) => {
if ( a > b) {
return 1;
}
if (a < b) {
return -1;
}
return 0;
});
console.log(sort);
return sort;
}
但我不知道如何重绘表格。我从 JSON 文件动态创建的表。为了开始排序,您需要单击字段名称,然后应显示已排序的表格。
const buildHeader = data =>
Object.keys(data)
.map(k => `<th>${k}</th>`)
.join("");
const buildRow = data =>
Object.keys(data)
.map(k => `<td>${data[k]}</td>`)
.join("");
let element = document.querySelector(".people");
function showPeople(people) {
let table = document.createElement("table");
table.classList.add("people__table");
let thead = document.createElement("thead");
thead.innerHTML = `<tr class="head">${buildHeader(people[0])}</tr>`;
table.appendChild(thead);
let tbody = document.createElement("tbody");
tbody.innerHTML = people
.map(p => `<tr class="person">${buildRow(p)}</tr>`)
.join("");
table.appendChild(tbody);
element.appendChild(table);
}
const customPeople = data =>
data.map((p, i) => {
return {
name: p.name,
sex: p.sex,
born: p.born,
died: p.died,
age: p.died - p.born,
mother: p.mother,
father: p.father,
};
});
showPeople(customPeople(ANCESTRY_FILE));
最佳答案
像这样的 sortTable
函数就可以完成这项工作:
function sortTable(tbody, index, ascending) {
Array.prototype.slice.call(tbody.children).sort(
(tr1, tr2) => tr1.children[index].textContent.localeCompare(tr2.children[index].textContent) * (ascending ? 1 : -1)
).forEach(tr => tbody.appendChild(tr));
}
// demonstration
(function(){
const thead_tr = document.getElementById('thdtr');
const tbody = document.getElementById('tbd');
function makeCell() {
const td = document.createElement('td');
td.appendChild(document.createTextNode(Math.round(Math.random() * 999999999).toString(36)));
return td;
}
function makeRow() {
const tr = document.createElement('tr');
for(let i = 0; i < thead_tr.children.length; i++) tr.appendChild(makeCell());
return tr;
}
// adds click-to-sort functionality
Array.prototype.forEach.call(thead_tr.children, (th, index) => {
let asc_toggle = false; // false will start off in ascending order
th.addEventListener('click', event => sortTable(tbody, index, asc_toggle = !asc_toggle));
});
// fills the table with random alphanumeric data
for(let i = 0; i < 100; i++) tbody.appendChild(makeRow());
}());
<table>
<thead>
<tr id="thdtr">
<th>col 1</th>
<th>col 2</th>
<th>col 3</th>
</tr>
</thead>
<tbody id="tbd">
</tbody>
<table>
我的 sortTable
函数是一个通用的就地表排序函数,应该适用于任何表。它接受 3 个参数:
tbody
-DOMElement
- 对tbody
元素或table
元素本身的引用,以包含者为准tr
(行)元素。index
-Number
- 排序依据的列的索引(从0
开始)。ascending
-Boolean
- 顺序是升序 (true
) 还是降序 (false
)<
与您当前代码一起使用的示例用法:
sortTable(document.querySelector('.people__table tbody'), 0, true);
关于javascript - 如何在纯 JavaScript 的帮助下对表格进行排序和重新生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55146615/