【问题标题】:jQuery's :first and :last on the first children of an elementjQuery 的 :first 和 :last 用于元素的第一个子元素
【发布时间】:2009-08-23 20:50:12
【问题描述】:

我有一些带有多个<tr> rows 的简单表(多个,全部带有 class="parent")。这些行中的<td> 单元格有自己的表格。我正在尝试定位 first (父)表的<tr> 行,如下所示:

HTML:

<table class="parent"> 
  <tr> <-- match with :first 
    <td> 
      <table> 
        <tr><td></td></tr> 
        <tr><td></td></tr> 
      </table> 
    </td> 
  </tr> 
  <tr> <-- match with :last 
    <td> 
      <table> <-- so ignore this child ..
        <tr><td></td></tr> 
        <tr><td></td></tr> <-- .. and do NOT match this <tr> with :last 
      </table> 
    </td> 
  </tr> 
</table>

jQuery:

$('table.parent').each(function() { 
  $(this).find('tr:first').dostuff(); 
  $(this).find('tr:last').dostuff(); 
});

:first &lt;tr&gt; 工作正常,因为它始终是父级的 &lt;tr&gt;。但是当我尝试选择:last &lt;tr&gt; 时,它将匹配嵌套表的最后一个&lt;tr&gt;,而不是父表的最后一个&lt;tr&gt;。如何告诉 jQuery 只查看父表中的 &lt;tr&gt;s,而不在可能的子表中进一步搜索?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    我建议稍微修改您的选择器,以确保它适用于将&lt;tbody&gt; 附加到表的浏览器(如 Firefox 和 Chrome):

    //tested
    $('table.parent > tbody').each(function() {
       $(this).children('tr:first').text('hello').css('background-color', 'red');
       $(this).children('tr:last').text('hello').css('background-color', 'red');
    });
    

    【讨论】:

      【解决方案2】:

      而不是.find()(查找所有后代)尝试.children(),它仅查找直接子代:

      $(this).children('tr:first').dostuff();
      

      【讨论】:

        猜你喜欢
        • 2012-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-05
        • 1970-01-01
        • 2013-01-11
        相关资源
        最近更新 更多