使用javascript sort()排序表 [英] Sorting table using javascript sort()
问题描述
我正在尝试对表格进行排序。我已经看过几个jQuery和JavaScript解决方案通过各种方式实现这一点,但是,没有看到任何使用JavaScript的本机sort()方法。也许我错了,但在我看来,使用sort()会更快。
I am trying to sort a table. I've seen several jQuery and JavaScript solutions which do this through various means, however, haven't seen any that use JavaScript's native sort() method. Maybe I am wrong, but it seems to me that using sort() would be faster.
下面是我的尝试,但是,我肯定错过了一些东西。我想做的是可行的,还是应该抛弃它?理想情况下,我想远离innerHTML和jQuery。谢谢
Below is my attempt, however, I am definitely missing something. Is what I am trying to do feasible, or should I abandon it? Ideally, I would like to stay away from innerHTML and jQuery. Thanks
var index = 0; //Index to sort on.
var a = document.getElementById('myTable').rows;
//sort() doesn't work on collection
var b = [];
for (var i = a.length >>> 0; i--;) {
b[i] = a[i];
}
var x_td, y_td;
b.sort(function(x, y) {
//Having to use getElementsByTagName is probably wrong
x_td = x.getElementsByTagName('td')[index].data;
y_td = y.getElementsByTagName('td')[index].data;
return x_td == y_td ? 0 : (x_td < y_td ? -1 : 1);
});
推荐答案
A td
元素没有 .data
属性。
如果你想要的文本内容如果只有一个文本节点,则在 .data
之前使用 .firstChild
。
If you wanted the text content of the element, and if there's only a single text node, then use .firstChild
before .data
.
然后,完成后,您需要将元素附加到DOM。对JavaScript元素数组进行排序对DOM没有任何影响。
Then when that is done, you need to append the elements to the DOM. Sorting a JavaScript Array of elements doesn't have any impact on the DOM.
此外,代替 getElementsByTagName(td)
,你可以使用 .cells
。
Also, instead of getElementsByTagName("td")
, you can just use .cells
.
b.sort(function(rowx, rowy) {
x_td = rowx.cells[index].firstChild.data;
y_td = rowy.cells[index].firstChild.data;
return x_td == y_td ? 0 : (x_td < y_td ? -1 : 1);
});
var parent = b[0].parentNode;
b.forEach(function(row) {
parent.appendChild(row);
});
如果您要比较的内容是数字,则应将字符串转换为数字。
If the content that you're comparing is numeric, you should convert the strings to numbers.
如果它们是文本字符串,那么你应该使用 .localeCompare()
。
If they are text strings, then you should use .localeCompare()
.
return x_td.localeCompare(y_td);
这篇关于使用javascript sort()排序表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!