无论是数字,字母还是日期,都可以通过单击标题标记对表进行排序 [英] Sort Table by click in header tag regardless of it is numeric, alphabetical or date
问题描述
我正在尝试通过
I'm trying to sort my table by javascript(only javascriptpure, not library and not framework, only javascriptpure).
Each column sort by clicking in every header tag and currently the sort is alphabetical but I need the sort will be numeric or alphabetical or date regardless of it. The data is a Json that come from the other side and could have numeric or alphabetical or date column.
This is my sort code:
function sortMainTable(_num) {
var table, rows, sw, i, x, y;
table = document.getElementById("mainTable");
sw = true;
while (sw) {
sw = false;
rows = table.getElementsByTagName("tr");
for (i = 1; i < (rows.length - 1); i++) {
x = rows[i].getElementsByTagName("td")[_num];
y = rows[i + 1].getElementsByTagName("td")[_num];
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
sw = true;
break;
}
}
}
}
Example json:
places = [{
"city": "Los Angeles",
"country": "USA",
"price:": "130.90",
"date": "02/12/2015"
},
{
"city": "Boston",
"country": "USA",
"price:": "11.40",
"date": "10/04/2014",
},
{
"city": "Chicago",
"country": "USA",
"price:": "320.40"
"date": "06/05/2017",
},
]
As I told above, I need the sort will be numeric or alphabetical or date regardless of it. (if the column is numeric, the table sort is order by numeric column, and if the column is alphabetical, the table sort is order by alphabetical column, if the column is date, the table sort is order by date column)
Any idea?
Thanks.
In JavaScript you can sort arrays of objects by using native Array.sort().
The
sort()
method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.Parameters
compareFunction Optional Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.
Return value
The sorted array. Note that the array is sorted in place, and no copy is made.
In your places
variable, you have to compare:
- Strings: By using
>
or<
sign, in the compare function. - Numbers: By using
-
sign, in the compare function. - Dates: You can convert string date (
02/12/2015
) to the timestamp equivalent (1423717200000
) by using:new Date("02/12/2015").getTime()
. So you can use-
sign, in the compare function.
I've rewrite your code to:
- Render the table with the
places
variable data, dynamically without ordering. - Render the data when it is sorted or not.
- Set the ordering control in the headers.
- Write a helper function to sort arrays according
key
,data
andtype
parameters. Returns the sorted data.
(function() {
var places = [{
"city": "Los Angeles",
"country": "USA",
"price": "130.90",
"date": "02/12/2015"
}, {
"city": "Boston",
"country": "USA",
"price": "11.40",
"date": "10/04/2014",
}, {
"city": "Chicago",
"country": "USA",
"price": "320.40",
"date": "06/05/2017",
}];
// 4.
function sortByKey(key, data, type) {
if (key === "price") {
if (type === "asc") { // ↑
data.sort(function(a, b) {
return (a[key] * 1) > (b[key]);
});
} else { // ↓
data.sort(function(a, b) {
return (a[key] * 1) < (b[key]);
});
}
} else if (key === "date") {
if (type === "asc") {
data.sort(function(a, b) {
return new Date(a[key]).getTime() - new Date(b[key]).getTime();
});
} else {
data.sort(function(a, b) {
return new Date(b[key]).getTime() - new Date(a[key]).getTime();
});
}
} else {
if (type === "asc") {
data.sort(function(a, b) {
return a[key] > b[key];
});
} else {
data.sort(function(a, b) {
return a[key] < b[key];
});
}
}
return data;
}
// 3.
function setSorterControl(data) {
// Remove the span class after sorting.
function reset() {
var elems = document.querySelectorAll("#mainTable th span"), i, len = elems.length, obj;
for (i = 0; i < len; i++) {
obj = elems[i];
obj.removeAttribute("class");
}
}
/*
Render the sorted data in the tbData element.
Set the data-type attribute with the proper value after click in the header control.
Set the proper span class when its clicked to sort the data.
*/
function sorter(e) {
var tbData = document.getElementById("tbData"), elem = e.target;
tbData.innerHTML = sortTable(sortByKey(elem.getAttribute("data-key"), data, elem.getAttribute("data-type")));
elem.setAttribute("data-type", elem.getAttribute("data-type") === "asc" ? "desc" : "asc");
reset();
elem.children[0].className = elem.getAttribute("data-type") === "asc" ? "desc" : "asc";
}
var elems = document.querySelectorAll("#mainTable th"), i, len = elems.length, obj;
for (i = 0; i < len; i++) {
obj = elems[i];
obj.onclick = sorter;
}
}
// 1.
function renderTable(data, type) {
var html = "", i, header = Object.keys(data[0]), lenHeader = header.length;
html += "<thead><tr>";
for (i = 0; i < lenHeader; i++) {
html += "<th data-key=\"";
html += header[i];
html += "\" data-type=\"asc\">";
html += header[i];
html += "<span></span></th>";
}
html += "</tr></thead><tbody id=\"tbData\">";
html += sortTable(data);
html += "</tbody>";
return html;
}
// 2.
function sortTable(data) {
var html = "",
i, j, len = data.length,
header = Object.keys(data[0]),
lenHeader = header.length;
for (i = 0; i < len; i++) {
html += "<tr>";
for (j = 0; j < lenHeader; j++) {
html += "<td>";
html += data[i][header[j]];
html += "</td>";
}
html += "</tr>";
}
return html;
}
document.getElementById("mainTable").innerHTML = renderTable(places);
setSorterControl(places);
})();
#mainTable {
border: solid 1px #ccc;
border-collapse: collapse;
}
#mainTable th,
#mainTable td {
padding: 5px;
}
#mainTable th {
background-image: linear-gradient(#bcbebf, #eff3f7);
cursor: pointer;
}
#mainTable th span {
pointer-events: none;
}
#mainTable th span:before {
content: "↕";
}
#mainTable th span.asc:before {
content: "↑";
}
#mainTable th span.desc:before {
content: "↓";
}
<table id="mainTable" border="1"></table>
这篇关于无论是数字,字母还是日期,都可以通过单击标题标记对表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!