2011-08-28 27 views
14

Mam aktualnie tabelę, która może zawierać N kolumn i N wierszy. W interfejsie mam przycisk do usunięcia ostatniej kolumny, ale nie mogę wymyślić, jak usunąć ostatnie td ze wszystkich wierszy, co dotychczas osiągnąłem, aby usunąć pierwszy wiersz td i ostatni wiersz td , ale zostaw resztę tam.jQuery usuń ostatnią kolumnę tabeli

Tu jest mój kodu (tylko usuwa ostatni tytuł aktualnie):

function removeTableColumn() { 
    /* 
     removeTableColumn() - Deletes the last column (all the last TDs). 
    */ 
    $('#tableID thead tr th:last').remove(); // Deletes the last title 
    $('#tableID tbody tr').each(function() { 
     $(this).remove('td:last'); // Should delete the last td for each row, but it doesn't work 
    }); 
} 

Am I czegoś brakuje?

Odpowiedz

28

To dlatego, że selektor :last pasuje tylko ostatni element w zbiorze.

Być może szukasz :last-child, która doskonale pasuje do elementów, które są ostatnim dzieckiem swojego rodzica:

+0

Nie wiedziałem o selektorze ': last-child', nice! –

6

:last zwraca ostatni element znaleziony przez selektor. Tak więc #tableID tr td:last zwróci tylko jeden td.

Można wybrać ostatni td każdego tr tego robić:

$('#tableID tr').find('th:last, td:last').remove(); 
+0

Działa doskonale, ale nie rozumiem, co robi kod. W każdym rzędzie dostaje dzieci td i th, ale co robi plaster? –

0

Możesz usunąć kolumnę z tabeli jak to

//remove the 1st column 
    $('#table').find('td,th').first().remove(); 

    //remove the 1st column 
    $('table tr').find('td:eq(1),th:eq(1)').remove(); 

    //remove the 2nd column 
    $('table tr').find('td:eq(1),th:eq(1)').remove(); 

    //remove the nth column 
    $('table tr').find('td:eq(n),th:eq(n)').remove(); 

dla reference