[英]Why does bracket notation seem to access more data then the jQuery object?
I'm still trying to understand the difference between $('foo')[0]
and $('foo').eq(0)
. 我仍然试图理解$('foo')[0]
和$('foo').eq(0)
之间的区别$('foo').eq(0)
。
As I understand it, the second one should access a jQuery object so I can use jQuery methods without having to wrap it again. 据我所知,第二个应该访问一个jQuery对象,所以我可以使用jQuery方法而不必再次包装它。
My question is this. 我的问题是这个。 Why does this (using "QuickWatch" in VS) seem to return direct access to the object, meaning that I can instantly access its properties: 为什么这(在VS中使用“QuickWatch”)似乎返回对对象的直接访问,这意味着我可以立即访问其属性:
$(this).children('SPAN')[0]
But when I use this, I get access to "prototype", "context", "prevObject", etc. and "[0]": 但是当我使用它时,我可以访问“prototype”,“context”,“prevObject”等,以及“[0]”:
$(this).children('SPAN').eq(0)
With the second method, it looks as though I'd still have to use [0]
to get access to the various properties? 使用第二种方法,看起来我仍然需要使用[0]
来访问各种属性?
I hope this makes sense, but I am trying to figure out the most elegant syntax. 我希望这是有道理的,但我试图找出最优雅的语法。
**Edited: - Not to beat this to death, but I changed the title to make more sense. **编辑: - 不要打败这个死亡,但我改变标题更有意义。 The original title was "...are they the same?" 最初的标题是“......它们是一样的吗?” And of course, the two things aren't the same. 当然,这两件事情并不相同。
In your case the children()
returns an array like object where you access the item on index 0 which is a raw DOM node. 在您的情况下, children()
返回一个类似于object的数组,您可以在其中访问索引0上的项目,该项目是原始DOM节点。
To get the same effect with .eq()
(which wraps the DOM node to a jQuery object) you would have to "evaluate it", ie. 要使用.eq()
(将DOM节点包装到jQuery对象)获得相同的效果,您必须“评估它”,即。 call [0]
on it. 打电话给[0]
。 If you want the same effect as the children()[0]
call but not do eq(0)[0]
, use .get(0)
instead. 如果你想要与children()[0]
调用相同但不执行eq(0)[0]
,请改用.get(0)
。
They are not the same. 她们不一样。 eq()
is a jQuery function. eq()
是一个jQuery函数。 []
accesses the array of jQuery objects directly. []
直接访问jQuery对象数组。
One advantage of using eq()
is it will work defensively. 使用eq()
一个优点是它可以防御性地工作。
For example: 例如:
<li>1</li>
<li>2</li>
<li>3</li>
If you do $('li').eq(4).text()
you get nothing. 如果你做$('li').eq(4).text()
你什么也得不到。 $('li').eq(-1).text()
gives you 3. $('li').eq(-1).text()
给你3。
I recommend using eq()
just to make sure. 我建议使用eq()
来确保。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.