2012-09-17 34 views
6

Tengo una tabla HTML como se muestra en http://jsfiddle.net/Lijo/auny3/. La tabla tiene 10 columnas, divididas en tres grupos de columnas. Necesito ocultar/mostrar el colgroup llamado "Associate Info" (incluyendo sus datos de filas) usando los botones "Show Associate" y "Hide Associate".Mostrar/Ocultar columna de tabla con colspan usando jQuery

¿Cuál es la mejor forma (en términos de rendimiento) para hacer esto usando jQuery?

Por favor, responda si tiene una respuesta mejor que http://jsfiddle.net/Lijo/auny3/8/

Nota: estoy generando la tabla utilizando ASP.Net GridView como se da en http://www.sacdeveloper.com/Community/Articles/tabid/86/ctl/ArticleView/mid/458/articleId/1/Group_columns_in_an_ASPNet_Gridview.aspx

Referencia:

  1. http://jsfiddle.net/Lijo/auny3/8/

  2. http://jsfiddle.net/Lijo/auny3/12/

  3. http://jsfiddle.net/Lijo/auny3/11/

  4. http://jsfiddle.net/Lijo/auny3/13/

respuesta seleccionada

  1. http://jsfiddle.net/Lijo/UqdQp/2/

enter image description here

+0

puede cambiar su html si es mejor de lo que es posible con jquery –

Respuesta

1

He generalizado la idea proporcionada por @Pioul. Por lo tanto, vota por favor a @Pioul también si te gusta esta respuesta.Este enfoque generalizado está disponible en http://jsfiddle.net/Lijo/UqdQp/10/

Referencias:

  1. Finding column index using jQuery when table contains column-spanning cells

  2. Select table cells based on the value in the cell

CÓDIGO

var associateStartElementString = "EmpID"; 
var financialStartElementString = "Type"; 

var associateHTMLElements; 
var financialHTMLElements; 

var associateHideClass = '.tableColGroupAssociate'; 
var financialHideClass = '.tableColGroupTransaction'; 

$(document).ready(function() { 



////////Hide Sections 


//Associate Hide 
$('.associateHide').live("click", function (e) { 
    e.preventDefault(); 


    var hideClass = associateHideClass; 
    associateHTMLElements = HideSection(hideClass, associateStartElementString); 

    $('.btnAssociate').show(); 

}); 

//Financial Hide 
$('.financialHide').live("click", function (e) { 
    e.preventDefault(); 

    var hideClass = financialHideClass ; 

    financialHTMLElements = HideSection(hideClass, financialStartElementString); 

    $('.btnFinancial').show(); 

}); 


////SHOW 
$('.btnAssociate').click(function() 
{ 
    associateHTMLElements.show(); 

     var firstHeaderLineElement = $(".resultGridTable").find(associateHideClass); 

    firstHeaderLineElement.show(); 

}); 


$('.btnFinancial').click(function() 
{ 
    financialHTMLElements.show(); 

     var firstHeaderLineElement = $(".resultGridTable").find(financialHideClass); 

    firstHeaderLineElement.show(); 

}); 



//Function 1 
function HideSection(hideClass, startElementString) 
{ 

var htmlElement = GetTableSections(hideClass, startElementString); 

var firstHeaderLineElement = $(".resultGridTable").find(hideClass); 

var variableToSet; 

if (!(htmlElement === undefined)) { 

    variableToSet = htmlElement; 
    htmlElement.hide(); 
    firstHeaderLineElement.hide(); 
} 

return variableToSet; 
} 


//Function 2 
function GetTableSections(hideClass, referenceHeaderCellValue) { 


var firstHeaderLineElement = $(".resultGridTable").find(hideClass); 
var colspan = parseInt(firstHeaderLineElement.attr("colspan")); 


var startElementIndex = GetNonColSpanIndex(referenceHeaderCellValue); 


if (startElementIndex > 0) { 

    startElementIndex = (startElementIndex - 1); 

    var selectedElements = $("tr:gt(0)") 
            .find("th:gt(" + startElementIndex + "):lt(" + colspan + "), td:gt(" + startElementIndex + "):lt(" + colspan + ")"); 

    return selectedElements; 

} 


} 

//Function 3 
function GetNonColSpanIndex(referenceHeaderCellValue) { 


var selectedCell = $("th").filter(function (i) { 
    return ($.trim($(this).html())) == referenceHeaderCellValue; 


}); 


var allCells = $(selectedCell).parent('tr').children(); 
var normalIndex = allCells.index($(selectedCell)); 
var nonColSpanIndex = 0; 


allCells.each(
    function (i, item) { 
     if (i == normalIndex) 
      return false; 

     var colspan = $(selectedCell).attr('colspan'); 
     colspan = colspan ? parseInt(colspan) : 1; 
     nonColSpanIndex += colspan; 
    } 
    ); 

return nonColSpanIndex; 
}; 


} 
); 
2

Hola ahora se utiliza para este

Jquery

$(document).ready(function(){ 

$("#show").click(function(){ 
    $("#showhide").show(); 
    }); 



    $("#hide").click(function(){ 
    $("#showhide").hide(); 
    }); 
}) 

y algunos cambios a su html

Live demo

+0

Funciona. Sin embargo, no podré usarlo. Estoy generando la tabla usando GridView. Envolver las columnas de la tabla dentro de una tabla puede no ser factible. ¿Puedes sugerir una alternativa? – Lijo

2

O puede utilizar nth-child selector:

$('input').click(function(){ 
    if($(this).val() == "Hide Associate"){ 
    $('th:nth-child(2), td:nth-child(2), th:nth-child(3):not(:first), td:nth-child(3), th:nth-child(4), td:nth-child(4), th:nth-child(5), td:nth-child(5)').hide(); 
    }else{ 
     $('th:nth-child(2), td:nth-child(2), th:nth-child(3):not(:first), td:nth-child(3), th:nth-child(4), td:nth-child(4), th:nth-child(5), td:nth-child(5)').show(); 
    } 
}); 
+0

Gracias. Traté de aplicar a otra sección también. Eso no funcionó. ¿Qué hay que cambiar para que funcione? http://jsfiddle.net/Lijo/auny3/9/ – Lijo

+1

@Lijo en la declaración else cambia 'hide' a' show'y para ocultar la "Información asociada" agrega 'th: nth-child (3): first' en los selectores Ver [This] (http://jsfiddle.net/alex_ball/auny3/10/) –

2

Aquí, trabajando con su código HTML actual, y seguirá trabajando si su Asociado información de la cabecera más columnas vez almacenados (el guión está buscando su colspan atributo a buscar el número apropiado de columnas).

$("input").on("click", function(e){ 
    e.preventDefault(); 

    var label = $(".resultGridTable .tableColGroupAssociate"), 
     colspan = parseInt(label.attr("colspan"), 10), 
     associate = $("tr:gt(0)") 
         .find("th:gt(0):lt("+ colspan +"), td:gt(0):lt("+ colspan +")") 
         .add(label); 

    if($(this).val() == 'Hide Associate') associate.hide(); 
     else associate.show(); 
});​ 

DEMO

+0

¿Puedes explicar cómo funciona? Estoy confundido acerca de ".add (etiqueta)" – Lijo

+1

Está almacenando cada elemento que queremos ocultar o mostrar en el objeto 'asociado'. Primero almacena las columnas 1 a 4 de las líneas 1 a 3, y luego agrega ([jQuery.add] (http://api.jquery.com/add/)) a esos elementos la celda "Asociar información". De esta forma, tenemos todos los elementos con los que queremos trabajar en un solo objeto jQuery: 'associate'. – Pioul

+0

Gracias. Entonces, estás usando indexación basada en cero en la explicación anterior. Además, el nombre de la variable "etiqueta" puede renombrarse como "primera línea". – Lijo

Cuestiones relacionadas