如果我们稍微改变你的标记,以便更好地处理这些联系,例如:
<div id="sort">
<a href="#name">Sort by name</a>
<a href="#year">Sort by year</a>
<a href="#fruit">Sort by fruit</a>
</div>
<ul id="things">
你们可以这样简单地探讨2点:
$("#sort a").click(function(e) {
var desc = $(this).hasClass("asc"),
sort = this.hash.substr(1),
list = $("#things");
list.append(list.children().get().sort(function(a, b) {
var aProp = $(a).find("span."+sort).text(),
bProp = $(b).find("span."+sort).text();
return (aProp > bProp ? 1 : aProp < bProp ? -1 : 0) * (desc ? -1 : 1);
}));
$(this).toggleClass("desc", desc)
.toggleClass("asc", !desc)
.siblings().removeClass("asc desc");
e.preventDefault();
});
您可以在这里测试,还有其他一些当然方法(以上可以进一步放下)。 你可以迅速开展这项工作。
下面是上述工作的详细情况:
- Take
#XXX
and get XXX
, that s the class we want to sort on (you could use a data-
attribute here)
- Grab the list - keep a reference so we don t keep selecting it
- Take the children (the
<li>
s), use .get()
to get the raw array of DOM elements
.sort()
that array by:
- Take
a
and b
passed in, those are <li>
elements
.find()
the <span>
we care to sort on in there
- Take the
.text()
of that <span>
- Return the comparison of that text (reverse if it we re
desc
, reversing the sort)
.append()
the sorted elements back to the list
- The last bit is just changing the sort styling, if it s already sorted ascending, change it to a
desc
class, otherwise make it an asc
class, and remove either class from any siblings.
If you have a very large number of elements, you ll want to take a different approach like the plugins posted in other answers...they parse the data on updates only and cache the result in objects, so there s less DOM traversal when sorting (which compared to everything else, is expensive).
如何改进上述工作(但作为实例可读性较低)的一个实例是选择<代码><span>各项内容,最初在甄选和上加以削减。
$("#sort a").click(function(e) {
var desc = $(this).hasClass("asc"),
sort = this.hash.substr(1),
list = $("#things");
$(list.children().detach().find("span."+sort).get().sort(function(a, b) {
var aProp = $.text([a]),
bProp = $.text([b]);
return (aProp > bProp ? 1 : aProp < bProp ? -1 : 0) * (desc ? -1 : 1);
})).parent().appendTo(list);
$(this).toggleClass("desc", desc)
.toggleClass("asc", !desc)
.siblings().removeClass("asc desc");
e.preventDefault();
});
您可在此测试该版本。