如何在jQuery中获取具有特定索引的元素
时间:2020-02-23 14:46:01 来源:igfitidea点击:
在本文中,我们将讨论如何获取具有特定索引的元素。
jQuery API为此操作提供了eq()方法。
jQuery eq()方法
jQuery eq()方法用于获取具有选定HTML元素的特定索引的元素。
您可以指定正整数或者负整数作为索引。
匹配元素的第一个元素的索引为0。
如果使用selector.eq(-1),它将返回最后一个元素,而selector.eq(0)将返回匹配的元素集中的第一个元素。
这是使用jQuery eq()方法的常规语法:
- 选择器.eq(索引)
index可以是任何正整数或者负整数。
jQuery eq()示例
以下示例演示了jQuery eq()方法的用法。
<!doctype html> <html> <head> <title>jQuery Traversing eq</title> <style> .highlight{ background: yellow; } .highlight1{ background: green; } div{ display: block; border: 3px solid black; color: black; padding: 5px; margin: 25px; width:250px; } </style> <script src="https://code.jquery.com/jquery-2.1.1.js"></script> </head> <body> <h2>jQuery eq() demo</h2> <div>My index is 0, also -6 from last</div> <div>My index is 1, also -5 from last</div> <div>My index is 2, also -4 from last</div> <div>My index is 3, also -3 from last</div> <div>My index is 4, also -2 from last</div> <div>My index is 5, also -1 from last</div> <script> $( "div" ).eq( "1" ).addClass("highlight"); $( "div" ).eq( "-6" ).addClass("highlight1"); </script> </body> </html>
在此示例中,我们可以看到jQuery eq()方法的使用。
$(" div").eq(1)将返回第二个div元素,并将颜色更改为黄色。
同样,当index为负时将搜索元素,因此-6将返回此html页面中的第一个div元素。