Une autre approche pour trier une table HTML. (basé sur W3.JS Tri HTML )
var collection = [{
"Country": "France",
"Date": "2001-01-01",
"Size": "25",
}, {
"Country": "spain",
"Date": "2005-05-05",
"Size": "",
}, {
"Country": "Lebanon",
"Date": "2002-02-02",
"Size": "-17",
}, {
"Country": "Argentina",
"Date": "2005-04-04",
"Size": "100",
}, {
"Country": "USA",
"Date": "",
"Size": "-6",
}]
for (var j = 0; j < 3; j++) {
$("#myTable th:eq(" + j + ")").addClass("control-label clickable");
$("#myTable th:eq(" + j + ")").attr('onClick', "w3.sortHTML('#myTable', '.item', 'td:nth-child(" + (j + 1) + ")')");
}
$tbody = $("#myTable").append('<tbody></tbody>');
for (var i = 0; i < collection.length; i++) {
$tbody = $tbody.append('<tr class="item"><td>' + collection[i]["Country"] + '</td><td>' + collection[i]["Date"] + '</td><td>' + collection[i]["Size"] + '</td></tr>');
}
.control-label:after {
content: "*";
color: red;
}
.clickable {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.w3schools.com/lib/w3.js"></script>
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>
<table id="myTable" class="w3-table-all">
<thead>
<tr>
<th>Country</th>
<th>Date</th>
<th>Size</th>
</tr>
</thead>
</table>