有很多人都会把这两种方法搞错,根据官方文档可以知道,eq( )返回的是jQuery对象,而get( )返回的则是DOM对象。
以下是官方对eq( )解释的原文:
Given a jQuery object that represents a set of DOM elements, the .eq( ) method constructs a new jQuery object from one element within that set. The supplied index identifies the position of this element in the set.
这句话的大意是:对一个代表一组DOM元素的jQuery对象应用eq( )方法时,eq( )方法会根据由索引值确定的元素创建一个新的jQuery对象。
示例:
HTML代码:
<div class="box"></div><div class="box"></div>
jQuery代码:
$box = $(".box");
alert($box.get(0).constructor == $);
结果:
true
而官方对get( )解释的原文是:
-
get(index)
- Retrieve one of the DOM elements matched by the jQuery object.
- 大意是:取得jQuery对象所代表的一组DOM元素中的一个匹配的元素。 get( )
- Retrieve the DOM elements matched by the jQuery object.
- 大意是:取得jQuery对象中的所有DOM元素,返回的是一个数组。
示例:
HTML代码:
<div class="box"></div><div class="box"></div>
jQuery代码:
$box = $(".box");
alert($box.get());
alert($box.get().constructor == Array);
结果:
[object HTMLDivElement],[object HTMLDivElement]
true