你需要切换有关信息在点击的按钮或链接上排序方向,
例如,商店等data-sort-direction
的数据属性,其取值为asc
和desc
或0
为升序排序和1
为降序排序类型内排序方向。
因此,在点击您检索该属性值,你根据其当前值asc
或desc
,0
或1
你的项目进行排序,然后在的.sort使用它()方法来决定你是否有返回1
,-1
或0
if (an > bn) {
return sortDirection === "asc" ? 1 : -1;
}
if (an < bn) {
return sortDirection ==="asc" ? -1 : 1;
}
return 0;
HTML
<button class="id" data-sort-direction="asc">Sort</button>
<table id="sort" class="table">
<tr data-name="John Doe">
<td>Mr. John Doe</td>
</tr>
<tr data-name="Trent Richardson">
<td>Mr. Trent Richardson</td>
</tr>
<tr data-name="Cindy Smith">
<td>Ms. Cindy Smith</td>
</tr>
<tr data-name="Bill Williams">
<td>Mr. Bill Williams</td>
</tr>
<tr data-name="Jane Doe">
<td>Mrs. Jane Doe</td>
</tr>
</table>
JS
var mylist = $('#sort'),
listitems = mylist.children('tbody').children('tr');
$('.id').on('click', function (e) {
var button = $(this),sortDirection = button.data('sort-direction');
// update data attribute for the next click
sortDirection === "asc"?button.data('sort-direction', "desc"):button.data('sort-direction', "asc");
listitems.sort(function (a, b) {
var an = a.getAttribute('data-name'),
bn = b.getAttribute('data-name');
if (an > bn) {
return sortDirection === "asc"?1:-1;
}
if (an < bn) {
return sortDirection ==="asc"?-1:1;
}
return 0;
});
listitems.detach().appendTo(mylist);
});
要当心,当您从<table>
标签检索<tr>
物品,甚至还有,如果你在你的HTML省略它的隐含<tbody>
,所以你必须得到<tr>
项目是这样的:
listitems = mylist.children('tbody').children('tr');
Fiddle with <tr>
Fiddle with <div>
你在第二个return语句中比较'compB'自身 – JLewkovich
你的'if条件'没有意义 –