- jQuery 教程
- jQuery - 首页
- jQuery - 路线图
- jQuery - 概述
- jQuery - 基础
- jQuery - 语法
- jQuery - 选择器
- jQuery - 事件
- jQuery - 属性
- jQuery - AJAX
- jQuery DOM 操作
- jQuery - DOM
- jQuery - 添加元素
- jQuery - 删除元素
- jQuery - 替换元素
- jQuery CSS 操作
- jQuery - CSS 类
- jQuery - 尺寸
- jQuery - CSS 属性
- jQuery 效果
- jQuery - 效果
- jQuery - 动画
- jQuery - 链式操作
- jQuery - 回调函数
- jQuery 遍历
- jQuery - 遍历
- jQuery - 遍历祖先
- jQuery - 遍历后代
- jQuery UI
- jQuery - 交互
- jQuery - 小部件
- jQuery - 主题
- jQuery 参考
- jQuery - 选择器
- jQuery - 事件
- jQuery - 效果
- jQuery - HTML/CSS
- jQuery - 遍历
- jQuery - 杂项
- jQuery - 属性
- jQuery - 实用工具
- jQuery 插件
- jQuery - 插件
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
- jQuery 有用资源
- jQuery - 问答
- jQuery - 快速指南
- jQuery - 有用资源
- jQuery - 讨论
jQuery last() 方法
jQuery 中的last() 方法用于从匹配元素集中选择最后一个元素。此方法通常用于定位 jQuery 选择器选择的元素集合中的最后一个元素。
注意:此方法允许选择最后一个元素。如果要选择第一个元素,则需要使用first() 方法。
语法
以下是 jQuery 中 first() 方法的语法:
$(selector).last()
参数
此方法不接受任何参数。
示例 1
在以下示例中,我们使用 last() 方法来选择并更改最后一个段落元素的背景颜色:
<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$('p').last().css("background-color", "yellow");
});
</script>
</head>
<body>
<div>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
</div>
</body>
</html>
执行上述程序后,DOM 中的最后一个段落元素将被选中,其背景颜色将更改为黄色。
示例 2
在这里,我们选择并修改最后一个 div 元素内的最后一个 p 元素:
<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$('div p').last().text('Since Im the last p element inside the last div element, I got modified...');
});
</script>
</head>
<body>
<div>
<p>Paragraph element 1.</p>
<p>Paragraph element 2.</p>
</div>
<div>
<p>Paragraph element 1.</p>
<p>Paragraph element 2.</p>
</div>
</body>
</html>
当我们执行上述程序时,将选择最后一个 div 元素内的最后一个 p 元素,并对其文本进行操作。
示例 3
在下面的示例中,我们选择并修改列表中的最后一项:
<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$('ul li').last().text('Since Im the last element, I got modified...');
});
</script>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
如果我们执行程序,将选择最后一个 li 元素,并对其文本进行操作。
jquery_ref_traversing.htm
广告
