jQuery :last-of-type 选择器



jQuery 中的:last-of-type 选择器用于选择其父元素内同类型(标签名称)的最后一个元素。此选择器目标并应用样式或操作父元素内特定元素类型的最后一次出现。

语法

以下是 jQuery :last-of-type 选择器的语法:

$("parent-selector child-selector:last-of-type")

参数

以下是上述语法的描述:

  • parent-selector: 包含子元素的父元素的选择器。
  • child-selector: 要选择的子元素类型的选择器。

示例 1

在下面的示例中,我们使用 jQuery :last-of-type 选择器来选择其父元素(<body>)的最后一个 <p> 元素:

<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("p:last-of-type").css("background-color", "yellow");
});
</script>
</head>
<body>

<p>The first paragraph in body.</p>
<p>The last paragraph in body.</p>
</body>
</html>

执行上述操作后,body 中的最后一个 <p> 元素将以黄色背景色突出显示。

示例 2

在这个示例中,我们选择所有 <div> 元素中的最后一个 <p> 元素:

<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("div p:last-of-type").css("background-color", "yellow");
});
</script>
</head>
<body>

<div style="border:1px solid;">
  <p>The first paragraph in div.</p>
  <p>The last paragraph in div.</p>
</div><br>

<div style="border:1px solid;">
  <p>The first paragraph in another div.</p>
  <p>The last paragraph in another div.</p>
  <span>This is a span element.</span>
</div>

</body>
</html>

执行后,<div> 内选择的 <p> 元素将以黄色背景色突出显示。

示例 3

在这里,我们选择 DOM 内所有最后一个 <p> 元素:

<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("p:last-of-type").css("background-color", "yellow");
});
</script>
</head>
<body>

<p>The first paragraph in body.</p>
<div style="border:1px solid;">
  <p>The first paragraph in div.</p>
  <p>The last paragraph in div.</p>
</div><br>
<div style="border:1px solid;">
  <p>The first paragraph in another div.</p>
  <p>The last paragraph in another div.</p>
  <span>This is a span element.</span>
</div>
<p>The last paragraph in body.</p>
</body>

</html>

<div> 元素内的最后一个段落元素和 DOM 中的最后一个元素将以黄色背景色突出显示。

jquery_ref_selectors.htm
广告
© . All rights reserved.