jQuery first()和last()函数示例
时间:2020-02-23 14:46:08 来源:igfitidea点击:
今天,我们将研究两个简单的遍历函数– first()和last()。
jQuery first()函数
jQueryfirst()方法用于从选定HTML元素中获取第一个元素。
您可以对返回的元素执行所需的操作。
这是使用jQuery first()的语法:
- first()
此方法不带任何参数。
jQuery first()示例
以下示例演示了jQuery first()方法的用法。
jquery-first.html
<html> <head> <title>jQuery Traversing First</title> <script src="https://code.jquery.com/jquery-2.1.1.js"></script> <style> .highlight{ background-color: yellow } </style> <script> $(document).ready(function(){ $("p span").first().addClass("highlight"); }); </script> </head> <body> <h1>Journal Dev</h1> <p>This is the first span element.</p> <p>This the second span element.</p> <p>This is the third span element.</p> </body> </html>
在此示例中,此代码中包含三个<p>元素。
first()方法返回第一个p元素的第一个span元素,并将背景色更改为黄色。
我们使用了jQuery addClass()方法来包含代码中定义CSS样式类。
下图显示了以上HTML页面产生的输出。
jQuery last()函数
jQuery last()方法用于从选定HTML元素中获取最后一个元素。
您可以对返回的元素执行所需的操作。
这是使用jQuery last()的语法:
- last()
此方法不带任何参数。
jQuery last()示例
以下示例演示了jQuery last()方法的用法。
jquery-last.html
<html> <head> <title>jQuery Traversing Last</title> <script src="https://code.jquery.com/jquery-2.1.1.js"></script> <style> .highlight{ background-color: yellow } </style> <script> $(document).ready(function(){ $("p span").last().addClass("highlight"); }); </script> </head> <body> <h1>Journal Dev</h1> <p>This is the first span element.</p> <p>This the second span element.</p> <p>This is the last span element.</p> </body> </html>
在此示例中,此代码中包含三个<p>元素。
last()方法返回最后一个p元素的最后一个span元素,并将背景色更改为黄色。
我们在jQuery中使用了addClass()方法来包含代码中定义CSS样式类。