定义jQuery";eq";
我很难把自己的头绕在桌子上。有人能给我解释一下它的用途吗?它是什么以及如何索引的 谢谢。使用此HTML:定义jQuery";eq";,jquery,Jquery,我很难把自己的头绕在桌子上。有人能给我解释一下它的用途吗?它是什么以及如何索引的 谢谢。使用此HTML: <ul> <li>Mario</li> <li>Luigi</li> <li>Princess</li> <li>Toad</li> </ul> .eq(i)返回集合中指定索引处的元素i 在您发布的链接的示例中: $(“p”).eq(1).
<ul>
<li>Mario</li>
<li>Luigi</li>
<li>Princess</li>
<li>Toad</li>
</ul>
.eq(i)
返回集合中指定索引处的元素i
在您发布的链接的示例中:
$(“p”).eq(1).css(“颜色”、“红色”)
它基本上说:“找到所有匹配$(“p”)的元素,然后取第二个元素,并将其颜色更改为红色。”
$(“p”)
匹配文档中的所有
元素。你现在有了一系列这些
$(“p”).eq(1)
将此集合仅减少为第二个元素
.css(“color”、“red”)
部分只对该元素进行操作,将其颜色更改为红色。查看文档中的示例:
$("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
听起来你可能被“索引”这个词迷住了 在这种情况下,“索引”指的是项目集合中的特定项目。因此,eq将允许您访问一组匹配元素中的单个项。要了解如何工作,我认为了解jQuery中的工作原理会有所帮助。当您指定
$([selector],[context])
//which is the same as
$([context]).find([selector])
返回的是一个jQuery对象(有时称为包装集),该对象在其他属性中具有一个以0
开头的属性,对于与选择器匹配的每个元素,该属性递增1。还设置了length
属性,这就是为什么jQuery对象的匹配元素可以像数组一样迭代(使用for循环或命令,如)
现在让我们看一下eq()
我们看到,eq()
是使用jQuery对象的命令实现的,所以我们也来看看它
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数组函数并将jQuery切片函数的
另一方面,命令更直接。让我们看看来源
// 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 ];
}
调用jQuery对象时,不使用num
参数的参数,使用JavaScript数组函数上的参数将jQuery对象转换为数组。如果定义了num
,则返回jQuery对象相应属性中的值,如下所示
$([selector]).get(0)
//is the same as
$([selector])[0]
似乎
.eq()
会被调用.get()
,如果它还没有被调用的话.get()
获取底层DOM元素。可能$($(($)p”).get(1))
与$($).eq(1)
相同。我认为$($(“p”).get(1))
语法唯一的缺点是它不透明。需要注意的是,eq()返回一个jQuery对象,该对象包含指定索引处的元素。这与[]或get()相反,后者返回普通的dom元素。+1用于通过源代码解释jQuery。真的很有帮助。谢谢
// 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 ];
}
$([selector]).get(0)
//is the same as
$([selector])[0]