gpt4 book ai didi

javascript - 为html表格实现数字排序?

转载 作者:可可西里 更新时间:2023-11-01 13:06:26 24 4
gpt4 key购买 nike

谁能帮我修改这段代码以支持数字排序。目前它只支持按字母顺序排序,我自己不是 js 编写者,我在网上找到了这个。我只需要它来排序数字,而不是字母。

奖励:是否可以让它支持数字和字符串

这是按字母顺序排序的工作链接。 jsfiddle.net

谢谢。

function sortTable(table, col, reverse) {
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}

function makeSortable(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
}(i));
}

function makeAllSortable(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'), i = t.length;
while (--i >= 0) makeSortable(t[i]);
}

window.onload = function () {makeAllSortable();};

最佳答案

这对字符串和数字都有效

if(!isNaN(a.cells[col].textContent) && !isNaN(b.cells[col].textContent))
return reverse * ((+a.cells[col].textContent) - (+b.cells[col].textContent))
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);

https://jsfiddle.net/oqr0mjc6/3/

关于javascript - 为html表格实现数字排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32480140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com