如何获得第一个元素而不是在 jQuery 中使用[0] ?

我是 jQuery 的新手,如果这是个愚蠢的问题,我道歉。

当我使用它查找使用 id 的元素时,我知道总是有一个匹配项,为了访问它,我将使用索引[0]。还有更好的办法吗? 举例来说。

var gridHeader = $("#grid_GridHeader")[0];
148598 次浏览

You can use .get(0) as well but...you shouldn't need to do that with an element found by ID, that should always be unique. I'm hoping this is just an oversight in the example...if this is the case on your actual page, you'll need to fix it so your IDs are unique, and use a class (or another attribute) instead.

.get() (like [0]) gets the DOM element, if you want a jQuery object use .eq(0) or .first() instead :)

http://api.jquery.com/eq/

$("#grid_GridHeader").eq(0)

$("#grid_GridHeader:first") works as well.

You can use the first selector.

var header = $('.header:first')

With the assumption that there's only one element:

 $("#grid_GridHeader")[0]
$("#grid_GridHeader").get(0)
$("#grid_GridHeader").get()

...are all equivalent, returning the single underlying element.

From the jQuery source code, you can see that get(0), under the covers, essentially does the same thing as the [0] approach:

 // Return just the object
( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );

You can use the first method:

$('li').first()

http://api.jquery.com/first/

btw I agree with Nick Craver -- use document.getElementById()...

You can try like this:
yourArray.shift()