在jQuery中选择多个元素类型

时间:2015-04-14 10:18:21

标签: javascript jquery html

我想选择td的{​​{1}}和th。目前我只能选择table td。我怎样才能缩短它?

th

2 个答案:

答案 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;
&#13;
&#13;