【问题标题】:jquery:how to use ">" and children() in tablejquery:如何在表中使用“>”和 children()
【发布时间】:2015-07-21 14:12:26
【问题描述】:

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/

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

【问题讨论】:

  • 你只是错过了 table 和 tr 之间的链接,所以 Arun P Johny 是正确的,你可以这样应用你的 css

标签: jquery jquery-selectors parent-child


【解决方案1】:

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

试试

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

【讨论】:

    【解决方案2】:

    符号>表示直系后代,在table和tr之间自动生成了一个tbody。试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多