jQuery的:首先是:最后一个元素的第一个子元素

我有一些简单的表(多个,都是class =“parent”),有多个

行。 这些行中的

单元格具有自己的表格。 我正在尝试定位第一 (父)表的

行,如下所示:

HTML:

  <-- match with :first  <-- match with :last 
<-- so ignore this child .. <-- .. and do NOT match this with :last

jQuery的:

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

:first

工作正常,因为它始终是父级的

。 但是当我尝试选择:last

,它将匹配嵌套表的最后一个

,而不是父表的最后一个

。 我如何告诉jQuery只查看父表中的

,并且不要在可能的子表中进一步搜索?

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

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

我建议稍微修改你的选择器,以确保它适用于将

附加到表(如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'); });