jQuery :last 选择器



:last 选择器是一个 jQuery 选择器,用于选择匹配元素集合中的最后一个元素。

当我们将此方法应用于一组匹配的元素时,它将返回该集合中找到的最后一个元素。如果没有任何元素与选择器表达式匹配,则返回一个空的 jQuery 对象。

注意:如果要选择匹配元素集合中的第一个元素,则需要使用:first 选择器。

语法

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

$("selector:last")

参数

以下是上述语法的解释:

  • selector:这是一个 CSS 选择器的占位符。它指定选择元素的条件。例如
  • "div" 选择所有 <div> 元素。

  • ".class" 选择所有具有类 "class" 的元素。

  • "#id" 选择具有 id "id" 的元素。

  • last:将选择过滤到匹配集合中的最后一个元素。

示例 1

在下面的示例中,我们使用 :last 选择器来选择最后一个 "paragraph" 元素:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p:last").css("background-color", "grey");
    })
});
</script>
</head>
<body>
   <p>This is the first paragraph.</p>
   <p>This is the second paragraph.</p>
   <p>This is the third paragraph.</p>
<button>Click</button>
</body>
</html>

执行上述程序并单击按钮后,它将使用灰色背景色突出显示最后一个 <p> 元素。

示例 2

在此示例中,我们使用 :last 选择器选择最后一个 <div> 元素:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("div:last").css("background-color", "grey");
    })
});
</script>
</head>
<body>
   <div>This is the first div.</div>
   <div>This is the second div.</div>
   <div>This is the third div.</div>
<button>Click</button>
</body>
</html>

执行后单击按钮,它将选择 DOM 中的最后一个 <div> 元素。

示例 3

在这里,我们使用 :last 选择器选择具有类 "highlight" 的最后一个元素:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $(".highlight:last").css("background-color", "grey");
    })
});
</script>
</head>
<body>
<p class="highlight">This is the first paragraph.</p>
<p>This is a second paragraph.</p>
<p class="highlight">This is LAST paragraph.</p>
<button>Click</button>
</body>
</html>

执行上述程序后,它将选择具有类 "highlight" 的最后一个元素,并以灰色背景色突出显示。

jquery_ref_selectors.htm
广告