Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [jQuery]Sortowanie tabeli względem jednego wiersza.
Forum PHP.pl > Forum > Po stronie przeglądarki > JavaScript
S_Olewniczak
Napisałem prosty kod do sortowania tabeli względem jednego wiersza, którego indeks znamy. Wygląda on tak:
Kod
//now sort table
if(sort_td_index!=undefined) {
     $(table + ' tr:gt(1)').each(function() {
        act_tr_1 = this;
        act_td_1 = $('td:eq(' + sort_td_index + ')' ,this).html().toLowerCase();
        $(table + ' tr:gt(1)').each(function() {
            act_td_2 = $('td:eq(' + sort_td_index + ')' ,this).html().toLowerCase();
            if ((act_td_2 > act_td_1 && sort_opt=='asc') || (act_td_2 < act_td_1 && sort_opt=='desc')) {
                $(act_tr_1).insertBefore(this);
            }
        });
        
     });
}//end if

Jednak nie działa jak należy. Co robię źle?
vokiel
1. czy table jest zmienną? Na co wskazuje?
2. console.log() => debugowanie:) (podgląd w firebugu)
3. zobacz jeśli this zastąpisz $(this)
4. skąd się bierze sort_td_index?

  1. <?php
  2. if(sort_td_index!=undefined) {
  3. // jesli table ma się donosić do tabeli to wrzuć w apostrofy $('table tr:gt(1)')
  4.     $(table + ' tr:gt(1)').each(function() {
  5.        act_tr_1 = $(this);
  6.        act_td_1 = $('td:eq(' + sort_td_index + ')' ,$(this)).html().toLowerCase();
  7. console.log(act_td_1); //debugowanie ;)
  8.        $(table + ' tr:gt(1)').each(function() {
  9.            act_td_2 = $('td:eq(' + sort_td_index + ')' ,$(this)).html().toLowerCase();
  10.            if ((act_td_2 > act_td_1 && sort_opt=='asc') || (act_td_2 < act_td_1 && sort_opt=='desc')) {
  11.                act_tr_1.insertBefore($(this));
  12.            }
  13.        });
  14.     });
  15. }
  16. ?>


btw. a czy sortowanie nie powinno być względem kolumny?
S_Olewniczak
Przepraszam, oczywiście chodziło mi o sortowanie względem kolumny. table jest zwykłym stringiem('#id_tabeli'). sort_td_index, jest indeksem kolumny wg której sortuje tabele.
vokiel
Teraz pozostaje zestaw pytań zastadniczych: Co nie działa? Jak działa?
Propomuję wczytać całą zawartość tabeli do zmiennej
Kod
var $rows = $(table).find('tbody tr').get();
i posortować ją przy użyciu funkcji sort z czystego js. A następnie całą zawartość wpisać spowrotem do tabeli. Przydatnym byłoby oddzielenie nagłówka tabeli poprzez thead od tbody - wtedy nie trzeba posiłkować się ' tr:gt(1)'.
S_Olewniczak
Próbowałem napisać ten kod według twoich wskazówek, ale nic mi nie wyszło. Proszę podaj mi w jaki sposób posortować tą tablicę i wstawić ją z powrotem do tabeli w HTML.
vokiel
  1. <?php
  2. var rows = $(table).find('tbody tr').get();
  3. rows.sort(function(a, b) {
  4.    var keyA = $(a).children('td').eq(sort_td_index ).text().toUpperCase();
  5.    var keyB = $(b).children('td').eq(sort_td_index ).text().toUpperCase();
  6.    if (keyA < keyB) return -1;
  7.    if (keyA > keyB) return 1;
  8.    return 0;
  9. });
  10. $.each(rows, function(index, row) {
  11.    $(table).children('tbody').append(row);
  12. });
  13. ?>


Ewentualnie jakiś plugin: tablesorter
S_Olewniczak
Działa! Po trzech dniach walki. Tu trochę poprawiony kod, poprawnie sortujący liczby. Może się komuś przyda.
Kod
/*
  * Natural Sort algorithm for Javascript
  *  Version 0.2
  * Author: Jim Palmer (based on chunking idea from Dave Koelle)
  * Released under MIT license.
  */
function naturalSort (a, b) {
         // setup temp-scope variables for comparison evauluation
         var x = a.toString().toLowerCase() || '', y = b.toString().toLowerCase() || '',
                 nC = String.fromCharCode(0),
                 xN = x.replace(/([-]{0,1}[0-9.]{1,})/g, nC + '$1' + nC).split(nC),
                 yN = y.replace(/([-]{0,1}[0-9.]{1,})/g, nC + '$1' + nC).split(nC),
                 xD = (new Date(x)).getTime(), yD = (new Date(y)).getTime();
         // natural sorting of dates
         if ( xD && yD && xD < yD )
                 return -1;
         else if ( xD && yD && xD > yD )
                 return 1;
         // natural sorting through split numeric strings and default strings
         for ( var cLoc=0, numS = Math.max( xN.length, yN.length ); cLoc < numS; cLoc++ )
                 if ( ( parseFloat( xN[cLoc] ) || xN[cLoc] ) < ( parseFloat( yN[cLoc] ) || yN[cLoc] ) )
                         return -1;
                 else if ( ( parseFloat( xN[cLoc] ) || xN[cLoc] ) > ( parseFloat( yN[cLoc] ) || yN[cLoc] ) )
                         return 1;
         return 0;
}
finction sortTable(sort_td_index, table='#id_of_table') {
var rows = $(table).find('tbody tr').get();
rows.sort(function(a, b) {
    var keyA = $(a).children('td').eq(sort_td_index ).text();
    var keyB = $(b).children('td').eq(sort_td_index ).text();
return naturalSort(keyA, keyB);
  
});
$.each(rows, function(index, row) {
   $(table).children('tbody').append(row);
});
}
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.