我想选择td
的{{1}}和th
。目前我只能选择table
或 td
。我怎样才能缩短它?
th
答案 0 :(得分:6)
如果TD包含的数据不需要钻得太深,那么在:nth-child
之前使用直接子选择器:
$table.find('tr > :nth-child(' + colIndex + ')').css('color', 'red');
JSFiddle(基于@Rory McCrossan') http://jsfiddle.net/TrueBlueAussie/o8wwf1ze/1/
答案 1 :(得分:0)
您可以使用multiple selector
var colIndex = 2;
var $table = $('table')
$table.find('tr').find(
'th:nth-child('+colIndex+'),'+
'td:nth-child('+colIndex+')')
.css('color','red')

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</table>
&#13;