选择表列(jQuery)

时间:2009-09-27 17:21:54

标签: jquery select html-table cell

我想给FIRST和LAST列的所有(包括<th>)单元格一些特定的类,我试过这个:

$("table tr:first-child td:first-child").addClass("first-col-cell");
$("table tr:last-child td:last-child").addClass("last-col-cell");

..但它似乎不起作用。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

编辑:您的选择器非常接近:

<script type="text/javascript">
    $(function() {
        $("table tr td:first-child").text('hello');
        $("table tr td:last-child").text('goodbye');
    });
</script>

<table>
    <tr>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
    </tr>
</table>

答案 1 :(得分:1)

如果th元素很重要......不确定您是如何处理colspans的。

<!doctype html>
<table>
    <tr>
    <th></th>
    <td>blah</td>
        <td></td>
    </tr>
    <tr>
        <td colspan="2"></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
    <td>blah</td>
        <td></td>
    </tr>
    <tr>
        <td></td>
    <td>blah</td>
        <td></td>
    </tr>
</table>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
      $("table tr :first-child").text('first').css('background', 'yellow');
      $("table tr :last-child").text('last').css('background', 'brown');
    });
</script>

答案 2 :(得分:0)

尝试将其分解一点,你正在进行的遍历是不正确的

// This will take the first child which is a TD, within any TR in the table.
$("table tr td:first-child").addClass("first-col-cell");

// This will take the first child which is a TR within the table.
$("table tr:first-child").addClass("first-col-cell");

// Just like the above, except now we're doing the last occurances
$("table tr td:last-child").addClass("last-col-cell");
$("table tr:last-child").addClass("last-col-cell");

然后我们只需要确保标记是好的

<table>
<tr>
    <td>1</td>
    <td>1</td>
    <td>1</td>
    <td>1</td>
</tr>
<tr>
    <td>2</td>
    <td>2</td>
    <td>2</td>
    <td>2</td>
</tr>
<tr>
    <td>3</td>
    <td>3</td>
    <td>3</td>
    <td>3</td>
</tr>

然后jQuery应该通过以下结果遍历每个

<table>
    <tr class="first-col-cell">
        <td class="first-col-cell">1</td>
        <td>1</td>
        <td>1</td>
        <td class="last-col-cell">1</td>
    </tr>
    <tr>
        <td class="first-col-cell">2</td>
        <td>2</td>
        <td>2</td>
        <td class="last-col-cell">2</td>
    </tr>
    <tr class="last-col-cell">
        <td class="first-col-cell">3</td>
        <td>3</td>
        <td>3</td>
        <td class="last-col-cell">3</td>
    </tr>
</table>