jQuery - cómo seleccionar un tr que contiene th de?
-
22-08-2019 - |
Pregunta
El título lo dice casi todo.
Dada una tabla como
<table>
<tr>
<th>Header 1</td>
<th>Header 2</td>
</tr>
<tr>
<td>Datum 1</td>
<td> Datum 2</td>
</tr>
<tr>
<td>Datum 1</td>
<td> Datum 2</td>
</tr>
</table>
¿Cómo seleccionar la fila que contiene los encabezados y th ningún otro?
Solución
Expresión:
$(function() {
$("tr:has(th):not(:has(td))").hide();
});
o incluso simplemente:
$(function() {
$("tr:not(:has(td))").hide();
});
Ejemplo completo:
<html>
<head>
<title>Layout</title>
</head>
<body>
<table>
<tr>
<th>Header 1</td>
<th>Header 2</td>
</tr>
<tr>
<td>Datum 1</td>
<td> Datum 2</td>
</tr>
<tr>
<td>Datum 1</td>
<td> Datum 2</td>
</tr>
<tr>
<th>Header 3</th>
<th>Datum 2</td>
</tr>
</table>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.3.1");
google.setOnLoadCallback(function() {
$(function() {
$("tr:has(th):not(:has(td))").hide();
});
});
</script>
</body>
</html>
Otros consejos
Si es posible, sería ideal para encerrar el encabezado de la tabla dentro de un elemento
De este modo, la selección de su cabecera de la tabla podría ser tan simple como: O seleccionar sólo el Su margen de beneficio sería entonces más fácil de leer, y el estilo de su mesa se vuelve más fácil, como se puede orientar más fácilmente los elementos en la cabecera o el cuerpo de la tabla. seleccionará cada kthxbye:) Utilice el Probablemente no va a funcionar si usted tiene una mesa con No sé si es como consultas Dojo CSS3, pero se puede utilizar la clase de pseudo primer hijo, si lo admite jQuery: tr th: first-child o tr th: nth-child (1) Ver: http://www.456bereastreet.com/archive/200601/css_3_selectors_explained/ <table>
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
$('thead');
$('thead tr');
jQuery("tr:has(th)")
tr
que contiene al menos un th
:has
: $('tr:has(th)').addClass('sample')
th
y td
mixto de niños sin embargo.