:last vs :last-child 选择器

:last vs :last-child selector

我注意到 $( 'filter:last' ) 与 jQuery 中的 $( 'filter:last-child' ) 不同。

我尝试了 jQuery 文档,但很难理解 :last 的其他用途以及为什么它们都存在。

显然,:last 是 jQuery 扩展,不在 CSS 规范中。因此,我想到了它与传统 :last-child 有何不同的问题。还有,jQuery中恰好有一个.last()方法据说比$( 'filter:last' )效率更高,那么:last选择器有什么用呢?

它们非常相似。不同的是,如果你有类似

<div>
  <p>hi</p>
  <p>bye</p>
</div>
<div>
  <p>hi</p>
  <p>bye</p>
</div>

$('p:last-child') 将 select 两个 <p>bye</p> 元素,而 $('p:last') 将 select 仅是第二个元素。同样的事情也可以用 $('p').last() 完成,通过添加 :last 作为 select 或 jQuery 允许使用带有 :last 的过滤器而不必使过滤器的参数成为一个函数。

:last select或仅匹配单个元素, :last-child 可以匹配多个:每个 parent.

请参阅下面的示例以获得更好的说明-

<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>last-child demo</title>
  <style>
 span.solast {
   text-decoration: line-through;
  }
 </style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
 </head>
<body>

<div>
 <span>John,</span>
 <span>Karl,</span>
 <span>Brandon,</span>
 <span>Sam</span>
</div>
 <div>
  <span>Glen,</span>
  <span>Tane,</span>
  <span>Ralph,</span>
  <span>David</span>
 </div>
<table>
  <tr><td>First Row</td></tr>
  <tr><td>Middle Row</td></tr>
  <tr><td>Last Row</td></tr>
</table>

<table>
  <tr><td>Second Table First Row</td></tr>
  <tr><td>Second Table Middle Row</td></tr>
  <tr><td>Second Table Last Row</td></tr> 
</table>


<script>
$( "div span:last-child" )
 .css({ color:"red", fontSize:"80%" })
 .hover(function() {
    $( this ).addClass( "solast" );
  }, function() {
    $( this ).removeClass( "solast" );
  });

$( "table tr:last" ).css({ backgroundColor: "yellow", fontWeight: "bolder" 
});
</script>

</body>
</html>

你可以看到在上面的代码中 :last selector 只改变了一个 tr 的背景颜色黄色,而不是两个 tr,这意味着 :last selects 只有一个元素。而 :last-child 将 select 每个元素最后 child.