实现html表的数值排序
Implement numerical sorting for html table?
谁能帮我修改这个代码,以支持数值排序。目前它只支持按字母顺序排序,我自己不是一个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/您应该将比较代码更改为
return reverse * ((+a.cells[col].textContent) - (+b.cells[col].textContent))
Javascript中的一元+
可用于将字符串转换为其数值。
对可以包含数字和非数字的单列进行排序比较棘手,因为您需要建立可传递的排序标准…例如:
- 所有类似数字的字符串出现在其他字符串之前
- 类数字字符串按照数值排序
- 其他字符串按字母顺序排序
function xcmp(a, b) {
if (isNan(a)) {
if (isNan(b)) {
return a.localeCompare(b);
} else {
return +1; // a non-numeric, b numeric: a > b
}
} else {
if (isNan(b)) {
return -1; // a numeric, b non-numeric: a < b
} else {
return a - b;
}
}
}
更简单的标准,如"如果它们都是数字,将它们作为数字进行比较,否则将它们作为字符串进行比较",就不能很好地工作了,因为
- "2"& lt;"10"
- "10"& lt;"10"
- "10"& lt;"2"
。您可以创建逻辑"循环",对于这些循环,排序的概念是没有意义的。
在您的排序函数中,您可以尝试将a.cells[col].textContent.trim()
转换为数字。如果不是数字,就按词序比较,否则就比较
相关文章:
- 使用html和Javascript进行客户端排序
- 使用Handontable在同一列中用纯文本和html对问题进行排序
- 如何移动/重新排序html表行
- 使用javascript/JQM对JSON对象进行排序并附加到html中
- 如何在javascript和/或jquery中对具有多列的HTML表进行排序
- 复杂的排序html表
- 排序html表列客户端没有第三方以外的jquery
- 如何排序html表的月份名称与年
- 排序html表根据列表的复选框在表列
- 用小数正确排序HTML下拉菜单
- 如何排序html表后,改变它与javascript函数
- 用行分类动态排序HTML表
- 排序HTML "LI"按重复次数和字母顺序排列
- 使用javascript或jquery排序html中的列
- 按降序排序HTML表
- 可选择jqueryui重新排序html标记内容
- jQuery - 动态排序 html 表行,不使用 ui-sortable
- 这是用jQuery重新排序HTML的有效方法吗?
- 重新排序html表行
- 排序HTML表,通过JQuery添加