.get(index)
and .eq(index)
- both return a single "element" from a jQuery object array, but they return the single element in different forms.
- returns it as a jQuery object, meaning the DOM element is wrapped in the jQuery wrapper, which means that it accepts jQuery functions.
- return a raw DOM element. You may manipulate it by accessing its attributes and invoking its functions as you would on a raw DOM element. But it loses its identity as a jQuery-wrapped object, so a jQuery function
won't work.
简言之:eq()获取的是jquery对象,能够使用jquery方法,get()获取的是原生dom元素,不能使用jquery方法.
Example:
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <meta http-equiv="X-UA-Compatible" content="IE=edge">
6 <meta name="viewport" content="width=device-width, initial-scale=1">
7 <title>eq() And get()</title>
8 </head>
9 <body style="height:2000px;">
10 <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
11 <div id="outer_div">
12 <div>
13 <input text value="AAA"><br>
14 <input text value="BBB"><br>
15 <input text value="CCC"><br>
16 <input text value="DDD"><br>
17 </div>
18 </div>
19 <script>
20 $(document).ready(function(){
21 var $inputEq = $('#outer_div').find("input").eq(2);
22 var $inputGet = $('#outer_div').find("input").get(2);
23 console.log("inputEq :"+$inputEq);
24 console.log("inputGet:"+$inputGet);
25 console.log("inputEqValue :"+$inputEq.val());
26 console.log("inputGetValue :"+$inputGet.value);
27 });
28 // Results:
29 /*
30 inputEq :[object Object]
31 inputGet:[object HTMLInputElement]
32 inputEqValue :CCC
33 inputGetValue :CCC
34 */
35 </script>
36 </body>
37 </html>
相关:
- .eq( index )
- .eq( indexFromEnd )
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
$( "li" ).eq( 2 ).css( "background-color", "red" );
$( "li" ).eq( -2 ).css( "background-color", "blue" );
- jQuery( ":eq(index)" )
- jQuery( ":eq(-index)" )
- .get( index )
1 <ul>
2 <li id="foo">foo</li>
3 <li id="bar">bar</li>
4 </ul>
5 console.log( $( "li" ).get( 0 ) );
- .get()
- Retrieve the elements matched by the jQuery object.
- All of the matched DOM nodes are returned by this call, contained in a standard array.
1 <ul>
2 <li id="foo">foo</li>
3 <li id="bar">bar</li>
4 </ul>
5 // javascript
6 console.log( $( "li" ).get() );
7 // result
8 [<li id="foo">, <li id="bar">]