2009-12-20 23 views
5

Tengo una aplicación web Zend Framework (PHP) que tiene una tabla con muchas filas.¿Cómo ocultar/mostrar las filas de la tabla usando jQuery?

  • 99.9% del tiempo, el usuario tomará medidas en la primera o segunda fila.
  • 00.1% del tiempo, el usuario tendrá que retroceder y tomar medidas en una fila diferente.

Así que solo necesito mostrar las primeras filas en la carga de la página, y mantener el resto disponible por el bien del historial.

Me gustaría acortar la tabla de alguna manera. Estoy pensando, usando jQuery, tal vez hacer algo donde se muestran las primeras 5 filas (el resto está oculto), y en la parte inferior de la tabla, hay un enlace para mostrar 5 filas más.

alt text http://img64.imageshack.us/img64/2479/5rowtable.png

¿Qué opinas? ¿Cómo podría lograr esto con jQuery?

Respuesta

23

Así es como me gustaría hacer esto (demo here):

Guión

var numShown = 5; // Initial rows shown & index 
var numMore = 5; // Increment 

var $table = $('table').find('tbody'); // tbody containing all the rows 
var numRows = $table.find('tr').length; // Total # rows 

$(function() { 
    // Hide rows and add clickable div 
    $table.find('tr:gt(' + (numShown - 1) + ')').hide().end() 
     .after('<tbody id="more"><tr><td colspan="' + 
       $table.find('tr:first td').length + '"><div>Show <span>' + 
       numMore + '</span> More</div</tbody></td></tr>'); 

    $('#more').click(function() { 
     numShown = numShown + numMore; 
     // no more "show more" if done 
     if (numShown >= numRows) { 
      $('#more').remove(); 
     } 
     // change rows remaining if less than increment 
     if (numRows - numShown < numMore) { 
      $('#more span').html(numRows - numShown); 
     } 
     $table.find('tr:lt(' + numShown + ')').show(); 
    }); 

}); 
+0

eso es exactamente lo que estaba tratando de hacer. ¡Gracias! – Andrew

+0

¿Qué hace el '.end()' hacer, siguiendo el '.hide()'? – Cheeso

+0

'.end()' revierte la selección a la anterior ... por lo que en este caso el selector vuelve a '$ ('table')'. Obtenga más información al respecto aquí (http://docs.jquery.com/Traversing/end), también está el selector '.andSelf()' (http://docs.jquery.com/Traversing/andSelf) – Mottie

1

Claro que puedes hacer esto con jQuery. Probablemente lo haría de esta manera:

<table> 
<tbody id="new"> 
    <tr>...</tr> <!-- x5 --> 
    <tr><td><a href="#" id="toggle">Show Old</a></td></tr> 
</tbody> 
<tbody id="old"> 
    ... 
</tbody> 
</table> 

cargarlos oculto con CSS:

#old { display: none; } 

y:

$(function() { 
    $("#toggle").click(function() { 
    if ($("#old").is(":hidden")) { 
     $(this).text("Hide Old"); 
    } else { 
     $(this).text("Show Old"); 
    } 
    $("#old").slideToggle(); 
    return false; 
    }); 
}); 

Los jQuery ocultar/mostrar efectos pueden ser un poco extraño con mesa componentes sin embargo. Si es así cambiar la CSS para esto:

#old.hidden { display: none; } 

y:

$(function() { 
    $("toggle").click(function() { 
    if ($("#old").hasClass("hidden")) { 
     $(this).text("Hide Old"); 
    } else { 
     $(this).text("Show Old"); 
    } 
    $(this).toggleClass("hidden"); 
    return false; 
    }); 
}); 

Por supuesto que no consigue los efectos agradables de esta manera.

+0

Por supuesto, la desventaja es que necesita cargar todas esas filas y luego ocultarlas. ¿No sería una buena cosa ajax una mejor práctica para el uso del ancho de banda? :) – Rimian

+0

De acuerdo, y ¿ha notado que StackOverflow hace el mismo procesamiento del lado del cliente para ocultar sus etiquetas ignoradas? – Pool

2

Sé que esto es un viejo hilo, pero sólo en caso de que alguien más está buscando escribí este guión:

$(function() { 
/* initial variables */ 
var numRows = $('#ticketLinesTable').find('tr').length; 
var SHOWN = 5; 
var MORE = 20; 

/* get how many more can be shown */ 
var getNumMore = function(ns) { 
    var more = MORE; 
    var leftOver = numRows - ns; 
    if((leftOver) < more) { 
     more = leftOver; 
    } 
    return more; 
} 
/* how many are shown */ 
var getInitialNumShown = function() { 
    var shown = SHOWN; 
    if(numRows < shown) { 
     shown = numRows; 
    } 
    return shown; 
} 
/* set how many are initially shown */ 
var numShown = getInitialNumShown(); 

/* set the numMore if less than 20 */ 
var numMore = getNumMore(numShown); 

/* set more html */ 
if(numMore > 0) { 
    var more_html = '<p><button id="more">Show <span style="font-weight: bold;">' + numMore + '</span> More...</button></p>'; 
    $('#ticketLinesTable').find('tr:gt(' + (numShown - 1) + ')').hide().end().after(more_html); 
} 
$('#more').click(function(){ 
    /* determine how much more we should update */ 
    numMore = getNumMore(numShown); 
    /* update num shown */ 
    numShown = numShown + numMore; 
    $('#ticketLinesTable').find('tr:lt('+numShown+')').show(); 

    /* determine if to show more and how much left over */ 
    numMore = getNumMore(numShown); 
    if(numMore > 0) { 
     $('#more span').html(numMore); 
    } 
    else { 
     $('#more').remove(); 
    } 
}); 

}); 
Cuestiones relacionadas