Jstris table sort

add sorting to tables

目前為 2023-09-09 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Jstris table sort
  3. // @namespace
  4. // @version 0.1
  5. // @description add sorting to tables
  6. // @author mxmossy
  7. // @match https://*.jstris.jezevec10.com/*
  8. // @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
  9. // @grant none
  10. // @license MIT
  11. // ==/UserScript==
  12.  
  13. (function() {
  14. // adapted from https://stackoverflow.com/questions/14267781/sorting-html-table-with-javascript
  15. var getCellValue = function(tr, idx){ return tr.children[idx].innerText || tr.children[idx].textContent; }
  16.  
  17. var comparer = function(idx, asc) { return function(a, b) { return function(v1, v2) {
  18. return v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2);
  19. }(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
  20. }};
  21.  
  22. // do the work...
  23. Array.prototype.slice.call(document.querySelectorAll('th')).forEach(function(th) { th.addEventListener('click', function() {
  24. var table = th.parentNode;
  25. while(table.tagName.toUpperCase() != 'TABLE') table = table.parentNode;
  26. var tableBody = table.querySelector('tbody');
  27. Array.prototype.slice.call(table.querySelectorAll('tbody tr:nth-child(n+1)'))
  28. .sort(comparer(Array.prototype.slice.call(th.parentNode.children).indexOf(th), this.asc = !this.asc))
  29. .forEach(function(tr) { tableBody.appendChild(tr) });
  30. })});
  31.  
  32. })();