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

标签 jquery jquery-selectors parent-child

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>

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
});

结果:第一个表格的背景已更改,但第二个表格未更改。 似乎空格选择器有效,但“>”和“children()”选择器不起作用,为什么?

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

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

最佳答案

即使我们没有创建 tbody,默认情况下 dom 结构也会创建它,因此所有 tr 都将是 tbody/thead/tfooter 的子级 不是 本身

尝试

$("table:last > tbody > tr").css("background", "#ffbbbb"); 

关于jquery:如何在表中使用 ">"和children(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31531342/

相关文章:

jquery - 在jquery中选择根元素

linux - 如果父进程收集终止状态失败一次,内核将再次尝试发送 SIGCHLD

javascript - jQuery 通过 ID 获取子值

javascript - 使用 javascript(或 jQuery)选择和操作 CSS 伪元素,例如::before 和::after

html - 子 div 悬停不起作用

javascript - 获取单选按钮列表中选中的单选按钮的值

javascript - 在下拉菜单上滚动时如何防止正文滚动。?

javascript - 如何将 Javascript 变量传递给 HTML <a href> 标记的 NAME 属性?

javascript - 尝试获取 div 子级中的图像 url

javascript - jquery/javascript 在复制文本时保持换行