2011-05-27 27 views
5

Tengo un pequeño problema confuso con jQuery y seleccionando/diseñando una columna en una tabla.jQuery nth-child selector

El siguiente código funciona:

$(function() { 
     $("table").delegate('th.selcol','click', function(e) { 
     var iCol = $(this).parent().children().index(this)+1; 
     $("table tr td:nth-child(10)").each(function() { 
      $(this).toggleClass("colhighlight"); 
     }); 
     }); 
    }); 

Pero este código, cambiando el niño enésimo (10) a nth-child (iCol) produce un error "excepción no capturada: Error de sintaxis, expresión no reconocida:: nth-child "

$(function() { 
     $("table").delegate('th.selcol','click', function(e) { 
     var iCol = $(this).parent().children().index(this)+1; 
     $("table tr td:nth-child(iCol)").each(function() { 
      $(this).toggleClass("colhighlight"); 
     }); 
     }); 
    }); 

Cualquier ayuda sería muy apreciada.

Respuesta

14
 $("table tr td:nth-child(" + iCol + ")").each(function() { 
     $(this).toggleClass("colhighlight"); 
    }); 

nth-child espera un entero, no es una cadena, por lo que puede utilizar la concatenación de resolver su problema.

+0

Gracias, para la solución y explicación de "por qué" – chrisk

+1

nth-child también acepta algunas palabras clave y una ecuación. Consulte la documentación de jQuery a continuación: 'El índice de cada hijo que coincide, comenzando con 1, la cadena par o impar, o una ecuación (p. Ej .: nth-child (par),: nth-child (4n)) ' – Owen

3

Prueba esto:

"table tr td:nth-child("+iCol+")" 
2

Cambio en esto:

$(function() { 
    $("table").delegate('th.selcol','click', function(e) { 
     var iCol = $(this).parent().children().index(this)+1; 
     $("table tr td:nth-child(" + iCol + ")").each(function() { 
     $(this).toggleClass("colhighlight"); 
     }); 
    }); 
    }); 
0

probar esto:

$(function() { 
     $("table").delegate('th.selcol','click', function(e) { 
     var iCol = $(this).parent().children().index(this)+1; 
     $("table tr td:nth-child("+iCol+")").each(function() { 
      $(this).toggleClass("colhighlight"); 
     }); 
     }); 
    }); 

esperar que funcione :)

+0

Gracias, eso funciona. – chrisk

+0

@chrisk: genial, ¿te importaría seleccionar una de las respuestas como solución? –