我使用此代码对各种类型的数据(日期、数字、字符串等)进行排序。
它在大多数情况下都有效,但是当我尝试对包含负数的数字的列进行排序时,它无法正确排序。
假设我喜欢按降序对第 3 列进行排序。就像现在一样,它排序为 0,负数将被忽略。
function sortcolumn(value) {
// alert(value)
let table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("ControlPanelListOfPAGAVEISPendentesTable");
switching = true;
dir = "desc";
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].cells[value].textContent.trim().toLowerCase();
y = rows[i + 1].cells[value].textContent.trim().toLowerCase();
const num = /^\d/.test(x)
const date = num && x.indexOf("/") != -1;
if (date) {
let [dd, mm, yyyy] = x.split("/");
x = new Date(yyyy, mm - 1, dd, 15, 0, 0, 0).getTime();
[dd, mm, yyyy] = y.split("/");
y = new Date(yyyy, mm - 1, dd, 15, 0, 0, 0).getTime();
}
else if (num) {
x = +x.replace(",", ".")
y = +y.replace(",", ".");
}
if (dir == "asc") {
shouldSwitch = x > y
} else if (dir == "desc") {
shouldSwitch = x < y
}
if (shouldSwitch) break;
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
switchcount++;
} else {
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
table {
border-spacing: 0;
width: 100%;
border: 1px solid #ddd;
}
th, td {
text-align: left;
padding: 1px;
}
tr:nth-child(even) {
background-color: #f2f2f2
}
青春有我
相关分类