Как раскрасить четные (или нечетные) столбцы таблицы с помощью jQuery?(без добавления классов вручную)
Моя разметка:
<table> <caption>Table caption</caption> <thead> <tr><th scope="col">Table header 1</th><th scope="col">Table header 2</th><th scope="col">Table header 3</th><th scope="col">Table header 3</th></tr> </thead> <tbody> <tr><th scope="row">Table row header</th><td>Table data</td><td>Table data</td><td>Table data</td></tr> <tr><th scope="row">Table row header</th><td>Table data</td><td>Table data</td><td>Table data</td></tr> <tr><th scope="row">Table row header</th><td>Table data</td><td>Table data</td><td>Table data</td></tr> <tr><th scope="row">Table row header</th><td>Table data</td><td>Table data</td><td>Table data</td></tr> </tbody> </table>
(может содержать или не содержать атрибуты области или th теги)
th
Вы можете использовать селектор :nth-child() для этого:
:nth-child()
$('table tr :nth-child(2n)').css('background-color', '#eee');
Вы можете увидеть демо здесь , эта версия делает столбцы, независимо от того, является ли ячейка <th> или <td>, вы можете добавить ее туда (например, td:nth-child(2n)), если хотите делать только одно или другое. Если вы хотите выбрать другие столбцы, просто введите 2n+1.
<th>
<td>
td:nth-child(2n)
2n+1
Редактировать: Обновлено, чтобы исправить неверное прочтение вопроса.
Это должно работать:
$('tr > :nth-child(even)').css('background-color','#eee');
или
$('tr > :nth-child(odd)').css('background-color','#eee');