日期:2014-05-16  浏览次数:21035 次

(3)选择元素——(14)接触DOM元素(Accessing DOM elements)
Every selector expression and most jQuery methods return a jQuery object. This is almost always what we want, because of the implicit iteration and chaining capabilities that it affords.

每一个选择器表达式和大部分的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;

然而在我们的代码中还有有一些地方我们想要接触到DOM元素。比如,我们可能想让一系列元素可以让其他的js库使用。另外,我们可能需要接触到一个元素的名字,使用DOM元素的属性可以做到这一点。对这些公认很少出现的场景,jquery提供了.get()方法可以由jquery对象引用。我们将使用.get(0)。如果DOM元素是在一个循环中被需要的,我们将使用.get(index)。
因此,如果我们想要知道id是my-element的元素的名字,我们将使用下面的代码片段:
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元素自己扯了出来。