jQuery | eq()及其示例

jQuery是一个非常强大的工具,它可以帮助我们结合各种DOM遍历方法来随机或按顺序选择文档中的元素。大多数DOM遍历方法不会修改元素,否则会根据给定的条件过滤掉元素。 这个 eq()方法 是jQuery中的一个内置方法,用于直接定位所选元素,并返回具有特定索引的元素。 语法:

null
$(selector).eq(index)

参数: 这里的参数“index”指定元素的索引。 可以是正数或负数。 注:

  • 索引编号始终从0开始,因此第一个编号的索引为0(而不是1)。
  • 使用负数作为索引将从列表末尾开始索引计数。

显示eq()方法工作的jQuery代码:
代码#1:

< html >
< head >
< title >GeeksForGeeks articles</ title >
jquery/3.3.1/jquery.min.js"></ script >
< script type = "text/javascript" >
$(document).ready(function() {
$(".heading").eq(0).css("color", "red");
$(".heading").eq(2).css("color", "yellow");
});
</ script >
</ head >
< body >
< h1 class = "heading" >GeeksForGeeks</ h1 >
< h2 class = "heading" >GeeksForGeeks</ h2 >
< h3 class = "heading" >GeeksForGeeks</ h3 >
< h4 class = "heading" >GeeksForGeeks</ h4 >
</ body >
</ html >


输出: 图片[1]-jQuery | eq()及其示例-yiteyi-C++库 代码#2: 下面的代码将选择具有负索引的指定元素。

< html >
< head >
< title >GeeksForGeeks articles</ title >
libs/jquery/3.3.1/jquery.min.js"></ script >
< script type = "text/javascript" >
$(document).ready(function() {
$(".heading").eq(-2).addClass("style");
$(".heading").eq(-4).addClass("style");
});
</ script >
< style >
.style {
color: red;
font-family: fantasy;
font-size: 20px;
}
</ style >
</ head >
< body >
< ul >
< li class = "heading" >GeeksForGeeks</ li >
< li class = "heading" >GeeksForGeeks</ li >
< li class = "heading" >GeeksForGeeks</ li >
< li class = "heading" >GeeksForGeeks</ li >
</ ul >
</ body >
</ html >


输出: 图片[2]-jQuery | eq()及其示例-yiteyi-C++库

jQuery:eq()vs get())

  • .eq()将其作为jQuery对象返回,这意味着DOM元素被包装在jQuery包装器中,这意味着它接受jQuery函数。
  • .get()返回原始DOM元素的数组。
© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享