$(selector)[0] 在 jQuery 中是什么意思? [英] What does $(selector)[0] mean in jQuery?
问题描述
我不明白的语法是这样的:
The syntax that I don't understand is this:
$("#profilePhotoFileUpload")[0]
我经常看到这种语法,但我已经忽略了一段时间,因为我从未使用过它.但是现在,为了理解这篇文章中的代码 如何使用 Parse.com javascriptSDK 上传图像?,我不能再忽略它了.
I have been seeing this syntax pretty frequently and I've ignored it for a while because I never had to use it. But now, in order to understand the code from this post How do I upload an image using the Parse.com javascriptSDK?, I cannot ignore it any longer.
我知道 [0]
这种语法通常用于引用数组.但是对 id
的引用会生成某种类型的数组似乎有点奇怪.
I know that [0]
this syntax is used to refer to an array usually. But it seems a little weird that a reference to an id
would generate an array of some sort.
推荐答案
通过将 [0]
附加到 jQuery 对象将返回 第一个 DOM 元素.
By appending [0]
to the jQuery object will return the first DOM element.
当您在这里使用 id 选择器时,数组中将只有一个元素,因此使用 [0]
是有意义的.如果您选择多个元素,您还可以使用介于 0 和元素数量之间的任意数字,您可以获得相应的 DOM 元素.
As you're using id selector here, there will be only one element in the array so using [0]
makes sense. If you are selecting multiple elements you can also use any number which is between 0 and number of elements you can get corresponding DOM element.
来自 jQuery 文档
jQuery 对象包含从 HTML 字符串创建或从文档中选择的文档对象模型 (DOM) 元素的集合.由于 jQuery 方法通常使用 CSS 选择器来匹配文档中的元素,因此 jQuery 对象中的元素集通常称为匹配元素"或选定元素"集.
A jQuery object contains a collection of Document Object Model (DOM) elements that have been created from an HTML string or selected from a document. Since jQuery methods often use CSS selectors to match elements from a document, the set of elements in a jQuery object is often called a set of "matched elements" or "selected elements".
jQuery 对象本身的行为很像一个数组;它有一个 length
属性,对象中的元素可以通过它们的数字索引 [0]
到 [length-1]
来访问.请注意,jQuery 对象实际上并不是 Javascript Array 对象,因此它没有真正的 Array 对象的所有方法,例如 join()
.
The jQuery object itself behaves much like an array; it has a length
property and the elements in the object can be accessed by their numeric indices [0]
to [length-1]
. Note that a jQuery object is not actually a Javascript Array object, so it does not have all the methods of a true Array object such as join()
.
这篇关于$(selector)[0] 在 jQuery 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!