JQUERY1.9学习笔记 之基本过滤器(二) 等于选择器

等于选择器 :eq()

描述:选择与设定下标匹配的元素。
jQuery( ":eq(index)" )
jQuery( ":eq(-index)" )

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<title>find the third td</title>

<script src="js/jquery-1.9.1.min.js"></script>

</head>
<body>
<table border="1">
<tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>
<tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>
<tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>
</table>
<script>
$("td:eq(2)").css("color", "red");
</script>
</body>
</html>

例子:用三个不同的样式去证明:eq()是为选择单元素而设计的,
然而,:nth-child()或:eq()在一个循环结构中,如.each()就能
选择多个元素。

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<title>eq demo</title>
<style>

</style>
<script src="js/jquery-1.9.1.min.js"></script>
</head>
<body>
<ul class="nav">
<li>List 1, item 1</li>
<li>List 1, item 2</li>
<li>List 1, item 3</li>
</ul>
<ul class="nav">
<li>List 2, item 1</li>
<li>List 2, item 2</li>
<li>List 2, item 3</li>
</ul>
<script>
// Applies yellow background color to a single <li>
$("ul.nav li:eq(1)").css("background-color","#ff0");
// Applies italics to text of the second <li> within each <ul class="nav">
$("ul.nav").each(function(index){
$(this).find("li:eq(1)").css("font-style","italic");
});
// Applies red text color to descendants of <ul class="nav">
// for each <li> that is the second child of its parent
$("ul.nav li:nth-child(2)").css("color","red");
</script>
</body>
</html>

Example: Add a class to List 2, item 2 by targeting the second to last <li>

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<title>eq demo</title>
<style>
.foo{
color:blue;
background-color:yellow;
}
</style>
<script src="js/jquery-1.9.1.min.js"></script>
</head>
<body>
<ul class="nav">
<li>List 1, item 1</li>
<li>List 1, item 2</li>
<li>List 1, item 3</li>
</ul>
<ul class="nav">
<li>List 2, item 1</li>
<li>List 2, item 2</li>
<li>List 2, item 3</li>
</ul>
<script>
$("li:eq(-2)").addClass("foo");
</script>
</body>
</html>

原文地址:https://www.cnblogs.com/semcoding/p/3519400.html