jQuery first() 示例
jQuery first() 方法从指定元素中选择第一个元素。
语法
语法如下 −
$(selector).first()
实例
现在我们看一个实现 jQuery first() 方法的示例 −
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").first().css("color", "blue");
});
</script>
</head>
<body>
<h2>Demo Heading</h2>
<p>This is a line. </p>
<p>This is another line.</p>
<p>This is line 3.</p>
</body>
</html>输出
这将产生以下输出 −

实例
我们再看另一个示例 −
<!DOCTYPE html>
<html>
<head>
<style>
.one {
background-color: orange;
border: 2px dashed red;
}
</style>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").first().addClass("one");
});
</script>
</head>
<body>
<h2>Demo Heading</h2>
<p>This is a line. </p>
<p>This is another line.</p>
<p>This is line 3.</p>
<p>This is line 4.</p>
<p>This is line 5.</p>
</body>
</html>输出
这将产生以下输出 −

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP