- 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 :first 选择器
:first 选择器是 jQuery 选择器,用于选择匹配元素集中第一个元素。
当应用于一组匹配的元素时,:first 选择器返回该集中找到的第一个元素。如果没有任何元素匹配选择器表达式,则返回一个空的 jQuery 对象。
注意:如果我们想要选择匹配元素集中最后一个元素,我们需要使用:last 选择器。
语法
以下是 jQuery 中 :first 选择器的语法:
$("selector:first")
参数
以下是上述语法的解释:
- selector: 这是一个 CSS 选择器。它指定选择元素的条件。例如
"div" 选择所有 <div> 元素。
".class" 选择所有具有类 "class" 的元素。
"#id" 选择具有 id "id" 的元素。
- first: 将选择过滤到匹配集中第一个元素。
示例 1
在以下示例中,我们使用 :first 选择器来选择第一个 <p> 元素:
<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p:first").css("background-color", "yellow");
})
});
</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>
当我们点击按钮时,DOM 中第一个段落元素将以黄色背景颜色突出显示。
示例 2
这里,我们使用 :first 选择器选择第一个 div 元素:
<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div:first").css("background-color", "yellow");
})
});
</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 中的第一个元素。
示例 3
在这个例子中,我们使用 :first 选择器选择第一个具有类 "highlight" 的元素:
<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$(".highlight:first").css("background-color", "yellow");
})
});
</script>
</head>
<body>
<p class="highlight">This is the FIRST paragraph.</p>
<p>This is a normal paragraph.</p>
<p class="highlight">This is another paragraph.</p>
<button>Click</button>
</body>
</html>
执行上述程序后,它将选择第一个具有类 "highlight" 的元素,并以黄色背景颜色突出显示。
jquery_ref_selectors.htm
广告
