每一个选择器表达式和大部分的jquery方法返回了一个jquery对象。至几乎总是我们想要的,因为它提供了隐式迭代和链锁所用。
Still, there may be points in our code when we need to access a DOM elementdirectly. For example, we may need to make a resulting set of elements available to another JavaScript library. Additionally, we might need to access an element's tag name, which is available as a propertyof the DOM element. For these admittedly rare situations, jQuery provides the .get()method. To access the first DOM element referred to by a jQuery object, we would use .get(0). If the DOM element is needed within a loop, then we would use .get(index). So, if we want to know the tag name of an element with id="my-element", we would write the following code snippet:
var myTag = $('#my-element').get(0).tagName;
For even greater convenience, jQuery provides a shorthand for .get(). Instead of writing the preceding line, we can use square brackets immediately following the selector:
var myTag = $('#my-element')[0].tagName;
为了更好的便利性,jquery为get()提供了一个快捷方式。我们可以在选择器后面使用中括号,而不用写之前的代码:
var myTag = $('#my-element')[0].tagName;
It's no accident that this syntax appears to treat the jQuery object as an array of DOM elements; using the square brackets is like peeling away the jQuery wrapper to get at the node list, and including the index(in this case, 0) is like plucking out the DOM element itself.
毫无意外,这个语法看起来想是我们把jquery对象当成DOM元素数组来看待,使用方括号好像是去到了jquery对象的外包装,然后得到了dom元素列表,包括index(在这里是0),好像是把DOM元素自己扯了出来。