jQuery : eq() vs get()

2020-01-25 04:45发布

I'm new to jQuery, and I'm wondering what the difference is between jQuery's get() and eq() functions. I may misunderstand what the get() function does, but I thought it odd that I couldn't call a function on the returned on the returned element in the same line.

//Doesn't work
I.e.  $("h2").get(0).fadeIn("slow");

//Works
$("h2").eq(0).fadeIn("slow");

8条回答
我命由我不由天
2楼-- · 2020-01-25 05:24

jQuery eq() method selects a HTML element with a specific index number.

Here is an example of that

<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</body>

$( "body" ).find( "div" ).eq( 2 ).addClass( "red" );
// it finds the second div in the html body and change it to red color.

Source: http://www.snoopcode.com/JQuery/jquery-eq-selector

查看更多
老娘就宠你
3楼-- · 2020-01-25 05:27

get(0)(docs) returns the first DOM element in the set.

eq(0)(docs) returns the first DOM element in the set, wrapped in a jQuery object.

That's why .fadeIn("slow"); doesn't work when you do .get(0). A DOM element doesn't have a fadeIn() method, but a jQuery object does.

查看更多
登录 后发表回答