首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >定义jQuery "eq“

定义jQuery "eq“
EN

Stack Overflow用户
提问于 2009-09-15 17:06:11
回答 5查看 4.9K关注 0票数 7

我有一段困难的时间包裹我的头围绕jQuery eq。有人能给我解释一下它的用法吗?它的索引是什么以及如何索引?

谢谢。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2009-09-15 17:08:19

使用此HTML:

代码语言:javascript
复制
<ul>
    <li>Mario</li>
    <li>Luigi</li>
    <li>Princess</li>
    <li>Toad</li>
</ul>

和这个JavaScript:

代码语言:javascript
复制
alert($("ul li").eq(0).text()); // Mario
alert($("ul li").eq(1).text()); // Luigi
alert($("ul li").eq(2).text()); // Princess
alert($("ul li").eq(3).text()); // Toad
票数 11
EN

Stack Overflow用户

发布于 2009-09-15 17:09:46

.eq(i)返回位于指定索引i的集合中的元素。

在您发布的链接的示例中:

$("p").eq(1).css("color", "red")

它基本上是说:“找到所有匹配$("p")的元素,然后获取第二个元素,并将其颜色更改为红色。”

$("p")匹配文档中的所有<p>元素。现在,您已经拥有了这些内容的集合。

$("p").eq(1)将这个集合减少到只有第二个元素。

.css("color", "red")部件只是对该元素进行操作,将其颜色更改为红色。

票数 9
EN

Stack Overflow用户

发布于 2009-09-15 19:38:39

为了理解eq()是如何工作的,我认为理解$()在jQuery中是如何工作的是有帮助的。当您指定

代码语言:javascript
复制
$([selector],[context])

//which is the same as

$([context]).find([selector])

返回的是一个jQuery对象(有时称为包装集),除了其他属性外,它还有一个以0开头的属性,每个匹配选择器的元素都会递增1。还设置了length属性,这就是为什么可以像数组一样迭代jQuery对象的匹配元素(使用for循环或each([callback])等命令)。

现在让我们来看一下eq()的源代码

代码语言:javascript
复制
 eq: function( i ) {
  return this.slice( i, +i + 1 );
 },

我们可以看到,eq()是使用jQuery对象的slice()命令实现的,因此让我们也来看看这一点

代码语言:javascript
复制
 slice: function() {
  return this.pushStack( Array.prototype.slice.apply( this, arguments ),
   "slice", Array.prototype.slice.call(arguments).join(",") );
 },

此外,还需要查看pushStack(),这是一个在内部经常使用的命令

代码语言:javascript
复制
 // Take an array of elements and push it onto the stack
 // (returning the new matched element set)
 pushStack: function( elems, name, selector ) {
  // Build a new jQuery matched element set
  var ret = jQuery( elems );

  // Add the old object onto the stack (as a reference)
  ret.prevObject = this;

  ret.context = this.context;

  if ( name === "find" )
   ret.selector = this.selector + (this.selector ? " " : "") + selector;
  else if ( name )
   ret.selector = this.selector + "." + name + "(" + selector + ")";

  // Return the newly-formed element set
  return ret;
 },

我们可以看到,pushStack接受一个数组并返回一个新的jQuery对象。构成新jQuery对象的匹配元素的元素是通过在JavaScript数组slice函数上调用Function.apply并将jQuery切片函数的arguments作为argsArray传入来获得的。

另一方面,get()命令更为简单。让我们看看它的来源

代码语言:javascript
复制
 // Get the Nth element in the matched element set OR
 // Get the whole matched element set as a clean array
 get: function( num ) {
  return num === undefined ?

   // Return a 'clean' array
   Array.prototype.slice.call( this ) :

   // Return just the object
   this[ num ];
 }

在不使用num参数的实参的情况下调用时,将使用JavaScript数组slice函数上的Function.call将jQuery对象转换为数组。如果定义了num,则返回保存在jQuery对象的相应属性中的值,如下所示

代码语言:javascript
复制
$([selector]).get(0)

//is the same as

$([selector])[0]
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1428438

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档