定义jQuery“eq”
我很难在jQuery eq周围环顾自己。 有人可以向我解释它的用途吗? 它的索引是什么?
谢谢。
使用此HTML:
- Mario
- Luigi
- Princess
- Toad
这个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
.eq(i)
从指定索引i
的集合返回一个元素。
在您发布的链接的示例中:
$("p").eq(1).css("color", "red")
它基本上说:“查找匹配$(”p“)的所有元素,然后取第二个并将其颜色更改为红色。”
$("p")
匹配文档中的所有
元素。 你现在有了这些的集合。
$("p").eq(1)
仅将此集合减少为第二个元素。
.css("color", "red")
部分只是对该元素进行操作,将其颜色更改为红色。
要了解eq()
工作原理,我认为理解$()
在jQuery中是如何工作的。 当你指定
$([selector],[context]) //which is the same as $([context]).find([selector])
返回的是一个jQuery对象(有时称为包装集 ),除其他属性外,它具有以0
开头的属性,并且对于与选择器匹配的每个元素递增1。 还设置了一个length
属性,这就是为什么jQuery对象的匹配元素可以像数组一样迭代(使用for循环或命令,如each([callback])
)。
现在让我们来看看eq()
的来源
eq: function( i ) { return this.slice( i, +i + 1 ); },
我们看到eq()
是使用jQuery对象的slice()
命令实现的,所以让我们看一下
slice: function() { return this.pushStack( Array.prototype.slice.apply( this, arguments ), "slice", Array.prototype.slice.call(arguments).join(",") ); },
并且还需要查看pushStack()
,这是一个内部使用的命令
// 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 Array slice
函数上调用Function.apply
并将jQuery slice函数的arguments
作为argsArray
。
另一方面, get()
命令更直接。 我们来看看源代码
// 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
参数参数的情况下调用jQuery对象,使用JavaScript Array slice
函数上的Function.call
将jQuery对象转换为数组。 如果定义了num
,则返回jQuery对象的相应属性中保存的值,与以下内容大致相同
$([selector]).get(0) //is the same as $([selector])[0]
看看docs中的示例:
$("p").eq(1).css("color", "red") $("p") selects all paragraphs in your document .eq(1) selects the second element only .css("color", "red") applies css rule to the selected element
听起来你可能会被“索引”这个词所吸引。
在这种情况下,’index’指的是项集合中的特定项。 因此, eq将允许您访问匹配的元素集中的单个项目。