jquery:如何在表中使用">"和children()

xia*_*alu 4 jquery parent-child jquery-selectors

Html代码:

<table>
    <tr>
        <td>The first row</td> <td>The first row</td>
    </tr>
    <tr>
        <td>The second row</td> <td>The second row</td>
    </tr>
    <tr>
        <td>The third row</td> <td>The third row</td>
    </tr>
    <tr>
        <td>The forth row</td> <td>The forth row</td>
    </tr>
</table>
<hr>
<table>
    <tr>
        <td>The first row</td> <td>The first row</td>
    </tr>
    <tr>
        <td>The second row</td> <td>The second row</td>
    </tr>
    <tr>
        <td>The third row</td> <td>The third row</td>
    </tr>
    <tr>
        <td>The forth row</td> <td>The forth row</td>
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

jQuery代码:

$(function () {
    $("table:first tr").css("background", "#ffbbbb");   //work
    $("table:last>tr").css("background", "#ffbbbb");   //not work
    $("table:last").children("tr").css("background", "#ffbbbb");  //not work
});
Run Code Online (Sandbox Code Playgroud)

结果:第一个表的背景已更改,但第二个表未更改. 似乎空间选择器工作,但'>'和'children()'选择器没有,为什么?

工作示例: https ://jsfiddle.net/6knk67gd/1/

我已经检查了这两个选择器的用法,但仍然在我的代码中找不到任何问题.请告诉我如何正确使用它们,谢谢〜

Aru*_*hny 6

即使我们没有创建一个tbody,默认情况下dom结构会创建它,所以所有人都tr将成为一个tbody/thead/tfooter不属于table自己的孩子

尝试

$("table:last > tbody > tr").css("background", "#ffbbbb"); 
Run Code Online (Sandbox Code Playgroud)