Skrip ini dapat dipakai untuk menyortir tabel dengan tampilan yang sederhana:
JavaScript
// Original code: http://stackoverflow.com/a/14268260/1163000 // Usage: `makeSortable(elem);` (function() { function sortTable(table, col, reverse) { var tb = table.tBodies[0], // Use `<tbody>` to ignore `<thead>` and `<tfoot>` rows tr = Array.prototype.slice.call(tb.rows, 0); // Put rows into array reverse = -((+reverse) || -1); tr = tr.sort(function (a, b) { // Sort rows return reverse * (a.cells[col].textContent.trim().localeCompare(b.cells[col].textContent.trim())); }); for (var i = 0, len = tr.length; i < len; ++i) { tb.appendChild(tr[i]); // Append each row in order } } function makeSortable(table) { var th = table.tHead, i; th && (th = th.rows[0]) && (th = th.cells); if (th) { i = th.length; } else { return; // If no `<thead>` then do nothing } while (--i >= 0) (function(i) { var dir = 1; th[i].onmousedown = function() { for (var j = 0, jen = th.length; j < jen; ++j) { th[j].className = th[j].className.replace(/(^| )desc|asc( |$)/g, "$1$2"); } sortTable(table, i, (dir = 1 - dir)); this.className += dir === 1 ? " desc" : " asc"; return false; }; }(i)); } window.makeSortable = makeSortable; })();
CSS
.table-sortable { border-collapse:collapse; table-layout:fixed; width:100%; font:normal normal 13px/1.4 Arial,Sans-Serif; color:black; background-color:white; } .table-sortable th, .table-sortable td { margin:0; padding:5px 8px; border:none; vertical-align:top; text-align:left; } .table-sortable th { font-weight:bold; background-color:slategray; color:white; border-color:white; } .table-sortable tbody tr:nth-child(even) {background-color:whitesmoke} .table-sortable th {cursor:pointer} th.asc, th.desc {background-color:lightslategray} th.asc:before, th.desc:before { content:""; display:block; float:right; width:0; height:0; border:.4em solid transparent; } th.asc:before { border-bottom-color:inherit; border-top-width:0; margin-top:.4em; } th.desc:before { border-top-color:inherit; border-bottom-width:0; margin-top:.5em; }
HTML
<table class="table-sortable" id="table-1"> <thead> <tr><th>Header 1</th><th>Header 2</th><th>Header 3</th></tr> </thead> <tbody> <!-- Sortable rows --> <tr><td> ... </td><td> ... </td><td> ... </td></tr> <tr><td> ... </td><td> ... </td><td> ... </td></tr> <tr><td> ... </td><td> ... </td><td> ... </td></tr> ... </tbody> </table> <script>makeSortable(document.getElementById('table-1'));</script>
Meski masih ada sedikit kekurangan alasannya ialah fungsi sortir ini hanya menggunakan kecerdikan menurut abjad. Coba Anda klik pada header Harga. Hasilnya tidak akan sesuai dengan apa yang kita harapkan. Masih sedang mencari solusi yang paling gampang untuk menangani satuan harga pada fungsi ini…