JS Enables automatic sorting of click header tables (including numbers, strings, and dates) and js tables
As follows:
Demo address: click here
The main JS Code is as follows:
Var tbody = document. querySelector ('# tableSort '). tBodies [0]; var th = document. querySelector ('# tableSort '). tHead. rows [0]. cells; var td = tbody. rows; for (var I = 0; I <th. length; I ++) {th [I]. flag = 1; th [I]. onclick = function () {sort (this. getAttribute ('data-type'), this. flag, this. cellIndex); this. flag =-this. flag ;};}; function sort (str, flag, n) {var arr = []; // store DOM for (var I = 0; I <td. length; I ++) {arr. push (td [I]) ;}; // sort arr. sort (function (a, B) {return method (str,. cells [n]. innerHTML, B. cells [n]. innerHTML) * flag;}); // Add for (var I = 0; I <arr. length; I ++) {tbody. appendChild (arr [I]) ;};}; // sorting method function method (str, a, B) {switch (str) {case 'num ': // return a-B; break; case 'string': // return. localeCompare (B); break; default: // Date sorting. In IE8, the time cannot be set in the format '2017-12-12 '. It is replaced with'/'return new Date (. split ('-'). join ('/')). getTime ()-new Date (B. split ('-'). join ('/')). getTime ();};};
Complete instance code
<! DOCTYPE>
Summary
The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.