<
table
>
<
thead
>
<
tr
id
=
"headtr"
>
<
th
>3</
th
>
<
th
>2</
th
>
</
tr
>
</
thead
>
<
tbody
>
<
tr
>
<
td
>3</
td
>
<
td
>2</
td
>
</
tr
>
<
tr
>
<
td
>2</
td
>
<
td
>3</
td
>
</
tr
>
<
tr
>
<
td
>1</
td
>
<
td
>1</
td
>
</
tr
>
</
tbody
>
</
table
>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
$(
function
() {
$(
'#headtr th'
).each(
function
(index, el) {
$(el).click(
function
() {
// 这里要用get()获取dom数组
var
rows = $(
'tbody'
).children().get();
// 当前排序保存在tr里
var
bAsc = $(
this
).hasClass(
'asc'
);
if
(bAsc) {
$(
this
).removeClass(
'asc'
);
}
else
{
$(
this
).addClass(
'asc'
);
}
rows.sort(
function
(tr1, tr2) {
// 获取单元格里的内容
var
value1 = tr1.cells[index].innerHTML;
var
value2 = tr2.cells[index].innerHTML;
if
(bAsc) {
return
value1.localeCompare(value2);
}
else
{
return
value2.localeCompare(value1);
}
});
for
(
var
i = 0; i < rows.length; i++) {
$(
'tbody'
).prepend(rows[i]);
}
});
});
});
|