jQuery last() 方法返回被选元素的最后一个元素。如果需要获取第一个元素,可以使用first()方法。

语法

$(selector).last() 
该方法没有参数

例子

例1

获取最后一个p元素。

<html>

<head>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"> </script>
<script>
$(document).ready(function() {
	$("button").click(function(){
		$("p").last().css("background-color", "lightblue");
	});
});
</script>
</head>

<body id = "main">

<h2> jQuery last() 方法例子 </h2>
<div style = "border: 1px solid blue;">
div 
</div>
<p style = "border: 1px solid blue;">
这是第一个段落
</p>
<p style = "border: 1px solid blue;">
这是第二个段落
</p>

<h3 style = "border: 1px solid blue;">
 h3
</h3>
<p style = "border: 1px solid blue;">
这是第三个段落
</p>

<p>点击下面的按钮获取最后一个段落</p>
<button> 点击看看 </button>
</body>

</html>

例2

获取最后一个span元素

 <html>

<head>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"> </script>
<script>
$(document).ready(function() {
	$("button").click(function(){
		$("div span").last().css("background-color", "lightblue");
	});
});
</script>
<style>
div {
border: 1px solid blue;
}
</style>
</head>

<body id = "main">

<h2> jQuery last() 方法例子 </h2>
<div>
<span> span1 </span>
</div>
<br>
<div>
<span> span2 </span>
</div>
<br>
<div>
<span> span3 </span>
</div>
<br>
<div>
<span> span4 </span>
</div>
<p>点击下面的按钮获取最后一个span元素</p>
<button> 点击看看 </button>
</body>

</html>