Упорядочить данные столбцов в алфавитном порядке - PullRequest
0 голосов
/ 17 мая 2019

Как я могу поменять местами целые столбцы на основе алфавитного порядка заголовков столбцов в HTML, используя javascript или jquery?

Код:

<body>
  <table id="mytable">
    <tr>
      <th>abc</th>
      <th>pqr</th>
    </tr>
    <tr>
      <td>123</td>
      <td>345</td>
    </tr>
    <tr>
      <td>987</td>
      <td>235</td>
    </tr>
  </table>
</body>

Фактический:

abc pqr

123 456

987 235

Ожидаемый:

     pqr    abc
     456    123
     235    987

Я пытался для строк, это работало:

Я пробовал это для столбцов, но не получил результатов: -

 <script>
 function sortTable() {
   var table, rows, switching, i, j, temp, x, y, shouldSwitch;
   table = document.getElementById("myTable");
   rows=table.getElementsByTagName("TR");
   var col_length= table.getElementsByTagName("TD").length;
   var row_length= table.getElementsByTagName("TR").length;

   while (switching) {
     switching = false;
     r = table.getElementsByTagName("TR");
     headers=table.getElementsByTagName("TH");
     values=table.getElementsByTagName("TD");
     rows=table.rows;

     for (i = 0; i < (row_length); i++) {
       shouldSwitch = false;
       one from current row and one from the next:*/
       x = rows[0].getElementsByTagName("TH")[i];
       y = rows[0].getElementsByTagName("TH")[i+1];
       if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
         temp=headers[i+1].innerHTML;
         headers[i+1].innerHTML=headers[i].innerHTML;
         headers[i].innerHTML=temp;
         shouldSwitch = true;
         break;
       }
     }
    if (shouldSwitch) {
      and mark that a switch has been done:*/
       for(j=0;j<col_length/row_length;j++)
       {

         values[j].parentNode.insertBefore(values[j + 1], values[j]);
         switching = true;
       }

     }
   }

 }
 </script>

Теперь кто-нибудь может мне помочь?

...