jQuery的:首先和:最后一个元素的第一个子元素 [英] jQuery's :first and :last on the first children of an element

查看:85
本文介绍了jQuery的:首先和:最后一个元素的第一个子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some simple tables (multiple, all with class="parent") with multiple <tr> rows. The <td> cells within these rows have tables of their own. I'm trying to target the <tr> rows of the first (parent) tables, like so:

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< tr> 工作正常,因为它始终是父级的< tr> 。但是当我尝试选择:last< tr> 时,它将匹配最后一个< tr> 嵌套表的内容,而不是父表的最后一个< tr> 。我如何告诉jQuery只查看父表中的< tr> ,并且不要在可能的子表中进一步搜索?

The :first <tr> works fine, since that's always the <tr> of the parent. But when I try to select the :last <tr>, it'll match the last <tr> of the nested table, and not the last <tr> of the parent table. How can I tell jQuery to only look at the <tr>s that are in the parent table, and don't search any further in possible children tables?

推荐答案

而不是 .find()(找到所有后代)尝试 .children()只查找直接子项:

Instead of .find() (which finds all descendents) try .children() which finds only direct children:

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

这篇关于jQuery的:首先和:最后一个元素的第一个子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆