上班遇到的需求,點選table的標題可以做排序,紀錄一下。
請把要做排序的Table加入 class = "sortTable"
table格式記得要是有thead、tbody
<table>
<thead>
<th></th>
</thead>
<tbody>
<tr></tr>
</tbody>
</table>
如果是使用GridView的話記得要給屬性喔
gvTable.HeaderRow.TableSection = TableRowSection.TableHeader
//排序
$(".sortTable thead th").attr("dataSortType", "Desc");
$(".sortTable thead th").click(function() {
var table, rows, switching, index, x, y, shouldSwitch, targetIndex, dataSortType;
table = $(this).parents("table");
targetIndex = $(this).parents("table").find("th").index(this);
switching = true;
dataSortType = $(this).attr("dataSortType");
console.log('dataSortType :', dataSortType);
while (switching) {
switching = false;
rows = table.find("tbody tr");
for (i = 0; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[targetIndex].childNodes[0].nodeValue.trim();
y = rows[i + 1].getElementsByTagName("TD")[targetIndex].childNodes[0].nodeValue.trim();
if (x == "") {
x = rows[i].getElementsByTagName("TD")[targetIndex].innerText;
}
if (y == "") {
y = rows[i + 1].getElementsByTagName("TD")[targetIndex].innerText;
}
debugger;
let xText = "",
yText = "";
if (x.trim() != "") {
xText = isNaN(x.replace(/,|\s/g, '')) ? x : parseInt(x.replace(/,|\s/g, ''));
}
if (y.trim() != "") {
yText = isNaN(y.replace(/,|\s/g, '')) ? y : parseInt(y.replace(/,|\s/g, ''));
}
index = i;
if (dataSortType == "Desc") {
if (xText > yText) {
shouldSwitch = true;
break;
}
} else {
if (xText < yText) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
if (dataSortType == "Desc") {
rows[index].parentNode.insertBefore(rows[index + 1], rows[index]);
} else {
rows[index].parentNode.insertBefore(rows[index + 1], rows[index]);
}
switching = true;
}
}
if (dataSortType == "Desc") {
$(".sortTable thead th").attr("dataSortType", "Asc");
} else {
$(".sortTable thead th").attr("dataSortType", "Desc");
}
});
$(".sortTable thead th").hover(
function() {
$(this).css("text-decoration", "underline");
$(this).css("cursor", "pointer");
},
function() {
$(this).css("text-decoration", "none");
$(this).css("font-weight", "");
}
);